Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, Non-negati ve integers and empty spaces
.
Assume that the given expression was always valid.
Some Examples:
"1 + 1" = 2 "2-1 + 2" = 3 "(1+ (4+5+2)-3) + (6+8)" = 23
Note:do not use the eval
built-in library function.
Public classSolution { Public intCalculate (String s) {/*First of all... This is 10 or more of a single-value calculation or more than 10, there are two-digit??! There are two digits in the word is still more troublesome .... is not within 10, then how to judge the end of the number? Simple iterative solution by identifying characters one by one. One important thing is, the input was valid, which means the parentheses is always paired and in order. Only 5 possible input we need to pay attention: just traverse one side of the string and then judge each character. Digit:it should be one digit from the current number ' + ': number is over, we can add the previous number and start A new number '-': Same as Above ' (': Push the previous result and the sign into the stack, set result to 0, Just calculate the new result within the parenthesis. ') ': Pop out the top and the numbers from stack, first one are the sign before this pair of parenthesis, second is the Temporar Y result before this pair of parenthesis. We add them together. Finally If there is only one number, from the above solution, we haven ' t add the number to the result, so we do a check SE E if the Number is zero constructs a stack, holds the intermediate result and the symbol, when encounters the opening parenthesis, saves the result and the symbol before the opening parenthesis, the res is empty, calculates the result in the null number, encounters the right parenthesis, pops the top two elements of the stack, and adds the result in parentheses. The point to note is that when encountering the + or-number, the calculation is the last operation, at this time only need to save the sigh and the sum is empty*/Stack<Integer> stack=NewStack<integer>(); intRes=0; intSigh=1; intNum=0; for(intI=0;i<s.length (); i++){ CharC=S.charat (i); if(Character.isdigit (c)) {num=10*num+ (int) (c ' 0 '); }Else if(c== ' + ') {res+=num*sigh; Num=0; Sigh=1; }Else if(c== '-') {res+=num*sigh; Num=0; Sigh=-1; }Else if(c== ' (') {Stack.push (res); Stack.push (sigh); Res=0; Sigh=1; }Else if(c== ') ') {res+=num*sigh; Num=0; Res*=Stack.pop (); Res+=Stack.pop (); } } if(num!=0) {res+=sigh*num; } returnRes; }}
[Leedcode 224] Basic Calculator