Create a simple calculator that given a string of operators (+ - * and /) and numbers separated by spaces returns the value of that expression
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
접기
면접볼때는 달달 외워다녔던것 같은데 오랜만에하니까 영..깔끔하지도 않고
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
public class Calculator {
public static Double evaluate(String expression) {
// your code here
Map<String,Integer> weight = new HashMap<String,Integer>();
weight.put("+", 1);
weight.put("-", 1);
weight.put("*", 2);
weight.put("/", 2);
List<String> postfix = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer(expression," ");
Stack<String> stack = new Stack<String>();
while (tokenizer.hasMoreElements()) {
String token =tokenizer.nextToken();
if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
while(!stack.isEmpty() && weight.get(token) <= weight.get(stack.peek())) {
postfix.add(stack.pop());
}
stack.push(token);
}else {
postfix.add(token);
}
}
while(!stack.isEmpty()) {
postfix.add(stack.pop());
}
for (String str : postfix) {
if(str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) {
if(str.equals("+")) {
stack.push(String.valueOf(Double.parseDouble(stack.pop())+Double.parseDouble(stack.pop())));
}else if(str.equals("-")){
double temp = Double.parseDouble(stack.pop());
stack.push(String.valueOf(Double.parseDouble(stack.pop())-temp));
}else if(str.equals("*")){
stack.push(String.valueOf(Double.parseDouble(stack.pop())*Double.parseDouble(stack.pop())));
}else {
double temp = Double.parseDouble(stack.pop());
stack.push(String.valueOf(Double.parseDouble(stack.pop())/temp));
}
}else {
stack.push(str);
}
}
return Double.parseDouble(stack.pop());
}
}
접기