Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negativeintegers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2" Output: 7
Example 2:
Input: " 3/2 " Output: 1
Example 3:
Input: " 3+5 / 2 " Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
這道題是之前那道 Basic Calculator 的拓展,不同之處在於那道題的計算符號只有加和減,而這題加上了乘除,那么就牽扯到了運算優先級的問題,好在這道題去掉了括號,還適當的降低了難度,估計再出一道的話就該加上括號了。不管那么多,這道題先按木有有括號來處理,由於存在運算優先級,我們采取的措施是使用一個棧保存數字,如果該數字之前的符號是加或減,那么把當前數字壓入棧中,注意如果是減號,則加入當前數字的相反數,因為減法相當於加上一個相反數。如果之前的符號是乘或除,那么從棧頂取出一個數字和當前數字進行乘或除的運算,再把結果壓入棧中,那么完成一遍遍歷后,所有的乘或除都運算完了,再把棧中所有的數字都加起來就是最終結果了,參見代碼如下:
解法一:
class Solution { public: int calculate(string s) { long res = 0, num = 0, n = s.size(); char op = '+'; stack<int> st; for (int i = 0; i < n; ++i) { if (s[i] >= '0') { num = num * 10 + s[i] - '0'; } if ((s[i] < '0' && s[i] != ' ') || i == n - 1) { if (op == '+') st.push(num); if (op == '-') st.push(-num); if (op == '*' || op == '/') { int tmp = (op == '*') ? st.top() * num : st.top() / num; st.pop(); st.push(tmp); } op = s[i]; num = 0; } } while (!st.empty()) { res += st.top(); st.pop(); } return res; } };
在做了 Basic Calculator III 之后,再反過頭來看這道題,發現只要將處理括號的部分去掉直接就可以在這道題上使用,參見代碼如下:
解法二:
class Solution { public: int calculate(string s) { long res = 0, curRes = 0, num = 0, n = s.size(); char op = '+'; for (int i = 0; i < n; ++i) { char c = s[i]; if (c >= '0' && c <= '9') { num = num * 10 + c - '0'; } if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) { switch (op) { case '+': curRes += num; break; case '-': curRes -= num; break; case '*': curRes *= num; break; case '/': curRes /= num; break; } if (c == '+' || c == '-' || i == n - 1) { res += curRes; curRes = 0; } op = c; num = 0; } } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/227
類似題目:
參考資料:
https://leetcode.com/problems/basic-calculator-ii/
https://leetcode.com/problems/basic-calculator-ii/discuss/63003/Share-my-java-solution
https://leetcode.com/problems/basic-calculator-ii/discuss/63004/17-lines-C++-easy-20-ms