/** 224. Basic Calculator * 12.10 by Mingyang * encounters ' (' push the previous results and symbols into the stack. Encountered ') ' the symbol in the current result *stack is added to the previous result in the stack. */ Public intCalculate (String s) {Stack<Integer> stack =NewStack<integer>(); intresult = 0; intNumber = 0; intSign = 1; for(inti = 0; I < s.length (); i++){ Charc =S.charat (i); if(Character.isdigit (c)) { number= Ten * 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 parenthesisSign = 1; Result= 0; }Else if(c = = ') ') {result+ = sign *Number ; number= 0; Result*= Stack.pop ();//Stack.pop () is the before the parenthesisResult + = Stack.pop ();//Stack.pop () is the result calculated before the parenthesis } } if(number! = 0) Result + = sign *Number ; returnresult; }
224. Basic Calculator