227. Basic Calculator II

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

227. Basic Calculator II

227. Basic Calculator II

227. Basic Calculator II

LeetCode 227. 基本计算器 II(Basic Calculator II)

leetcode 227. Basic Calculator II ---------- java

Leetcode 227. Basic Calculator II JAVA语言