My sample and short Java code bate 93%


  • 1
    W
    public int calculate(String s) {
        if(s == null || s.length() < 1) return 0;
        int index = 0, ret = 0, pre = 0;
        char op = '+';
        while(index < s.length()) {
            while(index < s.length() && s.charAt(index) == ' ') index++;
            int cur = 0;
            while(index < s.length() && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                cur = 10 * cur + (s.charAt(index++) - '0');
            }
            if(op == '+' || op == '-') {
                ret += pre;
                pre = op == '+' ? cur : -cur;
            } else if(op == '*' || op == '/') {
                pre = op == '*' ? pre * cur : pre / cur;
            }
            if(index < s.length()) op = s.charAt(index++);
        }
        return ret + pre;
    }

Log in to reply
 

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