LeetCode 227. Basic Calculator II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85265679

基本计算器 II - 力扣 (LeetCode)

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.

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.

经典题啊啊
用两个栈分别存数字和运算符
atoi是c的函数,输入不能是string,需要是char数组,所以需要对string使用.c_str()变为char数组(指针)

class Solution
{
  public:
    int calculate(string s)
    {
        if (s.size() == 0)
            return 0;
        int res = 0;
        stack<int> stk;
        int num = 0;
        char lastop = '+';
        for (int i = 0; i < s.size(); i++)
        {
            if (s[i] >= '0' && s[i] <= '9')
            {
                num *= 10;
                num += s[i] - '0';
            }
            if ((s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') || i == s.size() - 1)
            {
                if (lastop == '+')
                    stk.push(num);
                if (lastop == '-')
                    stk.push(-num);
                if (lastop == '*')
                {
                    int topnum = stk.top();
                    stk.pop();
                    stk.push(num * topnum);
                }
                if (lastop == '/')
                {
                    int topnum = stk.top();
                    stk.pop();
                    stk.push(topnum / num);
                }
                lastop = s[i];
                num = 0;
            }
        }
        while (!stk.empty())
        {
            int topnum = stk.top();
            res += topnum;
            stk.pop();
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/85265679