[LeetCode] Basic Calculator II
Basic Calculator II
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +,-, *, and/operators. The integer division shoshould truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7" 3/2 " = 1" 3+5 / 2 " = 5
Note: Do not useeval
Built-in library function.
Credits:
Special thanks to @ ts for adding this problem and creating all test cases.
Solution:
Like Basic Calculator I, you only need to change the code to be converted into a suffix expression.
Class Solution {public: int calculate (string s) {string postS = getPostString (s); // obtain the suffix expression cout <postS; stack
Nums; int len = postS. length (); int num1, num2; for (int I = 0; I
= '0' & postS [I] <= '9') {num = num * 10 + (postS [I]-'0'); I ++ ;} I --; nums. push (num); break;} return nums. top ();} private: string getPostString (string s) {string postS = ""; stack
Op; int len = s. length (); for (int I = 0; I
= '0' & s [I] <= '9') {postS + = s [I]; I ++;} postS + = '#'; // separate the numbers I --; break;} while (! Op. empty () {postS + = op. top (); op. pop ();} return postS ;}};