Basic Calculator
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.
Using the stack, if you encounter an opening parenthesis ' (' press the previous value and the 1.-1 expression operation symbol into the stack, you encounter a closing parenthesis ') ', the operation symbol and value removal are calculated.
1 classSolution {2 Public:3 intCalculatestrings) {4 if(s.length () = =0)return 0;5stack<int>Mystack;6 intresult=0;7 intop=1;8 for(intI=0; I<s.length (); i++)9 {Ten if(s[i]>='0'&& s[i]<='9') One { A intnumber=s[i]-'0'; - while((i+1) <s.length () && s[i+1]>='0'&& s[i+1]<='9') - { thei++; -number=number*Ten+s[i]-'0'; - } -result+=op*Number ; + } - if(s[i]==' ') + { A Continue; at } - if(s[i]=='+') - { -op=1; - } - if(s[i]=='-') in { -op=-1; to } + if(s[i]=='(') - { the Mystack.push (result); *result=0; $ Mystack.push (OP);Panax Notoginsengop=1; - } the if(s[i]==')') + { Aop=mystack.top (); the Mystack.pop (); +result=op*result+mystack.top (); - Mystack.pop (); $op=1; $ } - } - returnresult; the } -};
[Leetcode]basic Calculator