标签:
/* * 224. Basic Calculator * 12.10 by Mingyang * 遇到 ‘(‘ 就把之前的结果和符号push进stack. 遇到‘)‘就把 当前结果*stack中的符号 再加上stack中之前的结果. */ public int calculate(String s) { Stack<Integer> stack = new Stack<Integer>(); int result = 0; int number = 0; int sign = 1; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(Character.isDigit(c)){ number = 10 * number + (int)(c - ‘0‘); }else if(c == ‘+‘){ result += sign * number; number = 0; sign = 1; }else if(c == ‘-‘){ result += sign * number; number = 0; sign = -1; }else if(c == ‘(‘){ //we push the result first, then sign; stack.push(result); stack.push(sign); //reset the sign and result for the value in the parenthesis sign = 1; result = 0; }else if(c == ‘)‘){ result += sign * number; number = 0; result *= stack.pop(); //stack.pop() is the sign before the parenthesis result += stack.pop(); //stack.pop() now is the result calculated before the parenthesis } } if(number != 0) result += sign * number; return result; }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5580201.html