227. Basic Calculator II(重點記錄上一個符號,每次判斷上一個符號)
阿新 • • 發佈:2020-12-02
Given a strings
which represents an expression,evaluate this expression and return its value.
The integer division should truncate toward zero.
Example 1:
Input: s = "3+2*2" Output: 7
Example 2:
Input: s = " 3/2 " Output: 1
Example 3:
Input: s = " 3+5 / 2 " Output: 5
Constraints:
1 <= s.length <= 3 * 105
s
consists of integers and operators('+', '-', '*', '/')
separated by some number of spaces.s
representsa valid expression.- All the integers in the expression are non-negative integers in the range
[0, 231- 1]
. - The answer isguaranteedto fit in a32-bit integer.
class Solution { public: //帶括號的話,用遞迴,更難一些(找到對應層級的括號並同時刪除)int calculate(string s) { //利用棧: 3+5/2*3轉化為 +3 +5 /2 *3 stack<int> nums; int n = s.size(); int num = 0,res =0,pre=0; char sign = '+'; for(int i=0;i<n;i++){ //if(isspace(s[i])) continue; 忽略不用管空格 if(isdigit(s[i])){ num= num*10+(s[i]-'0'); } if(!isspace(s[i]) && !isdigit(s[i]) || i == n-1){ switch (sign){ case '+': nums.push(num); break; case '-': nums.push(-num); break; case '*': pre=nums.top(); nums.pop(); nums.push(pre*num); break; case '/': pre=nums.top(); nums.pop(); nums.push(pre/num); break; } sign = s[i]; num = 0; } } while(!nums.empty()){ res += nums.top(); nums.pop(); } return res; } };