227. Basic Calculator II

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.

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 use the eval built-in library function.

计算表达式结果,表达式都为valid,而且只包含 空格, +-*/,和数字。

这道题是用stack模拟计算,本身不难,但是细节特别多。

1 使用2个stack一个存数,一个存操作

2 注意处理两位以上的数字,需要计算

3 先计算 */,因为有优先级

4 计算 +-的时候不能像*/那样取stack里两个数,进行计算然后push回去,因为这样是从右向左计算,结果会出错,eg   “1-1+1”, 应该等于1,但是从右向左计算就是-1

5 用stack的时候一定先判断stack是否为空,不然不能调用top会出现runtime error

想清楚过程,是当出现数字的时候才去检查操作符,遇见操作符则直接压栈。

代码如下:

class Solution {
public:
    int calculate(string s) {
        stack<int> nums;
        stack<char> ops;
        int i = 0;
        int num2 = 0;
        int res = 0;
        while(i < s.size()) {
            if (s[i] == ' ') i++;
            else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
                ops.push(s[i]);
                i++;
            }
            else {//当s[i]为数字的时候才判断op是什么
                num2 = 0;
                while (i < s.size() && s[i] >= '0' && s[i] <= '9') {//数字有两位以上需要计算
                    num2 = num2 * 10 + (s[i] - '0');
                    i++;
                }
                nums.push(num2);
                if (!ops.empty()) {//记住一定先判断ops是否为空,不然不能调用top
                    if (ops.top() == '*') {
                        int num2 = nums.top();
                        nums.pop();
                        int num1 = nums.top();
                        nums.pop();
                        nums.push(num1 * num2);
                        ops.pop();
                    }                
                    else if (ops.top() == '/') {
                        int num2 = nums.top();
                        nums.pop();
                        int num1 = nums.top();
                        nums.pop();
                        nums.push(num1 / num2);
                        ops.pop();
                    }
                }                
            }
        }
        
        while(!ops.empty()) {//再算加减
            int num = nums.top();
            nums.pop();
            char op = ops.top();
            ops.pop();
            if (op == '-') num = -num;//如何处理 减法,刚开始是取num1 num2进行计算,但是这样就是从右向左的顺序,计算结果出错
            res += num;
        }
        res += nums.top();
        nums.pop();
        return res;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值