Leetcode 第227題:Basic Calculator II--基本計算器Ⅱ(C++、Python)

題目地址:Basic Calculator II


題目簡介:

實現一個基本的計算器來計算一個簡單的字符串表達式的值。字符串表達式僅包含非負整數,+, - ,*,/ 四種運算符和空格 。整數除法僅保留整數部分。

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

 


題目解析:

只要將乘除相關計算先計算和位數大於1的數字準確找出,其他問題就是簡單的相加。用棧的思想,將需要計算加減的先存起來,減可看作加負數,於是將乘除變化成加減即可。

C++:

class Solution {
public:
    int calculate(string s) {
        long ans = 0, num = 0;
        int n = s.size();
        char op = '+';
        vector<int> temp;
        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 == '+') 
                    temp.push_back(num);
                if (op == '-') 
                    temp.push_back(-num);
                if (op == '*' || op == '/') 
                {
                    int tmp = (op == '*') ? temp.back() * num : temp.back() / num;
                    temp.pop_back();
                    temp.push_back(tmp);
                }
                op = s[i];
                num = 0;
            } 
        }
        while (!temp.empty()) 
        {
            ans += temp.back();
            temp.pop_back();
        }
        return ans;
    }
};

Python:

class Solution:
    def calculate(self, s: str) -> int:
        ans,num,n = 0, 0, len(s)
        op = '+'
        temp = []
        for i in range(n): 
            if s[i] >= '0':
                num = num * 10 + ord(s[i]) - ord('0')
            if (s[i] < '0' and s[i] != ' ') or i == n - 1:
                if (op == '+'):
                    temp.append(num)
                if (op == '-'):
                    temp.append(-num)
                if (op == '*' or op == '/'):
                    tmp = temp[-1] * num if (op == '*') else int(temp[-1] / num)
                    temp.pop()
                    temp.append(tmp)
                op = s[i]
                num = 0
        for t in temp: 
            print(t)
            ans += t
        return ans

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章