/** 227.Basic Calculator II * 2016-6-13 by Mingyang * This topic is different from I, here is the need to stack, here is the first encounter symbol, sign equals the symbol just met * and then continue to add and subtract, that is, whether plus or minus are deposited in the stack again-Microsoft onsite topic*/ Public intcalculate1 (String s) {intLen; if(s==NULL|| (len = s.length ()) ==0)return0; Stack<Integer> stack =NewStack<integer>(); intnum = 0; CharSign = ' + '; for(inti=0;i<len;i++){ if(Character.isdigit (S.charat (i))) {num= Num*10+s.charat (i)-' 0 '; } if((! Character.isdigit (S.charat (i)) && "!=s.charat (i)) | | I==len-1){ if(sign== '-') {Stack.push (-num); } if(sign== ' + ') {stack.push (num); } if(sign== ' * ') {Stack.push (Stack.pop ()*num); } if(sign== '/') {Stack.push (Stack.pop ()/num); } Sign=S.charat (i); Num= 0; } } intRe = 0; for(inti:stack) {Re+=i; } returnre; }
227.Basic Calculator II