首页 > 代码库 > 227. Basic Calculator II

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.

 解题思路:当前操作符如果是低优先级则可以计算之前的,否则更新当前的操作数

class Solution {
public:
    int calculate(string s) {
        stringstream in(++s++);
        char op;
        long res=0,temp=0,n;
        while(in>>op){
            if(op == + || op == -){
                res += temp;
                in>>temp;
                temp *= 44-op;
            }
            else {
                in>>n;
                if(op == *)
                    temp *= n;
                else temp /= n;
            }
        }
        return res;
    }
};

 

227. Basic Calculator II