题目:

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) {
        int result = 0, status = 1, term = 0;
        for (int i = 0; i < s.length(); ++i) {
            if(s[i] == '+') {
                status = 1;
                result += term;
                term = 0;
            }
            else if(s[i] == '-') {
                status = 2;
                result += term;
                term = 0;
            }
            else if(s[i] == '*') {
                status = 3;
            }
            else if(s[i] == '/') {
                status = 4;
            }
            else if (isdigit(s[i])) {

                int x = 0;
                for (; isdigit(s[i]); ++i) {
                    x = x * 10 + s[i] - '0';
                }
                -- i;

                switch(status) {
                    case 1:
                        term = x;
                        break;

                    case 2:
                        term = -x;
                        break;

                    case 3:
                        term *= x;
                        break;

                    case 4:
                        term /= x;
                        break;

                }
            }
        }

        return result + term;
    }
};

还是C++的解答明了,扫描一遍的过程中,记住了符号,对连续数字的10进制处理,把结果用加法运算累计起来。