LeetCode-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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Analysis:

Whether we can perform a+b depends on the operator after b, so for a+b*c*d/e+f+g, we just calculate like a+(b*c*d/e)+f+g.

Solution:

public class Solution {
    int index;

    public int calculate(String s) {
        if (s.isEmpty())
            return 0;
        s = s.trim();

        int preValue = 0;
        char preOper = '+';
        index = 0;
        while (index < s.length()) {
            // Get next number & operator.
            int nextNum = getInt(s);
            char nextOper = getOperator(s);
            if (nextOper == 'n') {
                preValue = operate(preValue, nextNum, preOper);
                break;
            }

            // if nextOper is '+' or '-', perform operation immediately.
            if (nextOper == '*' || nextOper == '/') {
                int nnNum = getInt(s);
                char nnOper = getOperator(s);
                // keep calculating until reaching '+','-', or end of string
                while (nnOper == '*' || nnOper == '/') {
                    nextNum = operate(nextNum, nnNum, nextOper);
                    nextOper = nnOper;
                    nnNum = getInt(s);
                    nnOper = getOperator(s);
                }
                nextNum = operate(nextNum, nnNum, nextOper);
                nextOper = nnOper;
            }
            preValue = operate(preValue, nextNum, preOper);
            preOper = nextOper;
        }
        return preValue;
    }

    public char getOperator(String s) {
        char oper = 'n';
        skipSpace(s);
        if (index < s.length()) {
            oper = s.charAt(index++);
        }
        return oper;
    }

    public int operate(int num1, int num2, char operator) {
        switch (operator) {
        case '+':
            return num1 + num2;
        case '-':
            return num1 - num2;
        case '*':
            return num1 * num2;
        case '/':
            return num1 / num2;
        }
        return 0;
    }

    public int getInt(String s) {
        skipSpace(s);
        int val = 0;
        while (index < s.length() && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
            val = val * 10 + (s.charAt(index++) - '0');
        }
        return val;
    }

    public void skipSpace(String s) {
        while (index < s.length() && s.charAt(index) == ' ') {
            index++;
        }
    }
}

 

posted @ 2016-08-31 06:35  LiBlog  阅读(139)  评论(0编辑  收藏  举报