Very concise Java solution


  • 0
    public int calculate(String s) {
            s = s.replaceAll(" ", "");
            int len = s.length();
            int res = 0, pre = 0, i = 0, sign = '+';
            while (i < len) {
                int cur = 0;
                while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                    cur = cur * 10 + s.charAt(i++) - '0';
                }
                if (sign == '+' || sign == '-') {
                    res += pre;
                    pre = (sign == '+' ? cur : -cur);
                } else if (sign == '*') {
                    pre *= cur;
                } else if (sign == '/') {
                    pre /= cur;
                }
                if (i < len) sign = s.charAt(i++);
            }
            return res + pre;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.