Simple JAVA Solution that beats 96.51% solutions


  • 0
    I

    My thoughts is simple: using two level evaluation. result = result +/- term. term = term */ num or term = num. Considering term = num can be merged to term = 1 * num, so set the default value of term to be 1 and default op to be *.

    So for char cur in String s:
    case '+' or '-': term = term (op) num, res += sign * term, reset num, term, op. Set sign.
    case '' or '/': term = term (op) num, reset num, set op.
    case '1' to '9': num = 10
    num + cur - '0'.

    And we must add one more add to result at last.

    The code is:

    public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0) return 0;
        int num = 0, term = 1, res = 0;
        int sign = 1; //1: '+', -1: '-'
        char op = '*'; 
        for(int i = 0; i < s.length(); i++){
            char cur = s.charAt(i);
            if(cur == '+' || cur == '-'){
                term = (op == '*') ? term * num : term / num;
                res += sign * term;
                term = 1;
                num = 0;
                op = '*';
                sign = (cur == '+') ? 1 : -1;
            }
            else if(cur == '*' || cur == '/'){
                term = (op == '*') ? term * num : term / num;
                num = 0;
                op = cur;
            }
            else if(cur >= '0' && cur <= '9') num = 10 * num + cur - '0';
        }
        term = (op == '*') ? term * num : term / num;
        res += sign * term; //the last character
        return res;
    }
    

    }


Log in to reply
 

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