Problem

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.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

You may assume that the given expression is always valid.
Do not use the eval built-in library function.

Solution

class Solution {
    public int calculate(String s) {
        s = s.trim().replaceAll(" ", "");
        if (s == null || s.length() == 0) return 0;
        long pre = 0;
        int res = 0, i = 0;
        char sign = '+';
        
        while (i < s.length()) {
            long cur = 0;
            while (i < s.length() && Character.isDigit(s.charAt(i))) {
                cur = cur*10 + (s.charAt(i)-'0');
                i++;
            }
            switch (sign) {
                case '+':
                    res += pre;
                    pre = cur; break;
                case '-':
                    res += pre;
                    pre = -cur; break;
                case '*':
                    pre *= cur; break;
                case '/':
                    pre /= cur; break;
            }
            if (i < s.length()) {
                sign = s.charAt(i);
                i++;
            }
        }
        
        res += pre;
        return res;
    }
}

linspiration
161 声望53 粉丝