Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,,, +
-
*
, /
operators and empty spaces
. The integer division should truncate toward zero.
Assume that the given expression was always valid.
Some Examples:
"3+2*2" = 7 "3/2" = 1 "3+5/2" = 5
Note:do not use the eval
built-in library function.
Taking 3 + 2 * 2 As an example, the focus of this problem is to process the 2 (push 2) and then update sign when the current character is found to be *.
Public classSolution { Public intCalculate (String s) {s= S.replace ("", "" "); intnum = 0; CharSign = ' + '; Stack<Integer> stack =NewStack<>(); for(inti = 0; I < s.length (); ++i) {if(Character.isdigit (S.charat (i))) {num= num * + (S.charat (i)-' 0 '); } if(! Character.isdigit (S.charat (i)) | | i = = S.length ()-1) { if(sign = = ' + ')) {stack.push (num); } Else if(sign = = '-')) {Stack.push (-num); } Else if(Sign = = ' * ')) {Stack.push (Stack.pop ()*num); } Else if(sign = = '/')) {Stack.push (Stack.pop ()/num);; } Sign=S.charat (i); Num= 0; } } intres = 0; for(intele:stack) {Res+=Ele; } returnRes; }}
Basic Calculator II