Problem Solving with Algorithms

반응형
import java.util.*; 

public class Calc {

  public double evaluate(String expr) {
    Stack<Double> st = new Stack<Double>();
    String number = "";
    for(int i = 0; i < expr.length(); i++) {
      char ch = expr.charAt(i);
      if( ('0' <= ch && ch <= '9') || ch == '.') {
        number += ch;
      } else if(ch == ' ') {
        if(number != "") {
            st.push(Double.parseDouble(number));
            number = "";
        }
      } else {
        switch(ch) {
            case '+':
              st.push(st.pop() + st.pop());
              break;
            case '-':
              st.push(-1*st.pop() + st.pop());
              break;
            case '*':
              st.push(st.pop() * st.pop());
              break;
            case '/':
              st.push(1/st.pop() * st.pop());
              break;
        } 
      }
    }
    
    if(number != "")
      st.push(Double.parseDouble(number));
    
    return (st.size() == 1)? st.pop() : 0;
  }
}

 

import java.util.Stack;

public class Calc {

  public double evaluate(String expr) {
    if (expr.equals("")) {
      return 0;
    }
  
    Stack<Double> stack = new Stack<Double>();
    String[] atoms = expr.split(" ");
    
    for (String atom: atoms) {
      Double a, b;
      switch (atom) {
        case "+": stack.push(stack.pop() + stack.pop()); break;
        case "-": b = stack.pop(); a = stack.pop(); stack.push(a - b); break;
        case "*": stack.push(stack.pop() * stack.pop()); break;
        case "/": b = stack.pop(); a = stack.pop(); stack.push(a / b); break;
        default:
          stack.push(Double.parseDouble(atom));
      }
    }
    
    return stack.pop();
  }
}
반응형
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band