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:
Note:do not use the Eval built-in library function.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Similar to the basic calculator. is a very ingenious solution.
Runtime:24ms
classSolution { Public:intCalculatestrings) {intLen=s.size ();if(S.empty ())return 0; Stack<int>Stintnum =0;CharSign =' + '; for(intI=0; i<len;i++) {if(IsDigit(S[i])) {num = num*Ten+s[i]-' 0 '; }if(!IsDigit(S[i]) &&"'!=s[i] | | i==len-1){if(sign=='-') {St.push (-num); }if(sign==' + ') {St.push (num); }if(sign==' * '){intTmp=st.top (); St.pop (); St.push (Tmp*num); }if(sign=='/'){intTmp=st.top (); St.pop (); St.push (Tmp/num); } sign = s[i]; num =0; } }intRe =0; while(!st.empty ()) {Re + = St.top (); St.pop (); }returnRe }};
Leetcode227:basic Calculator II