32ms java O(n) using two values for sum and multiply fyi


  • 0
    S

    Still thinking about more optimized codes..

    public class Solution {
    public int calculate(String s) {
        
        int sumVal = 0, mulVal = 0;
        char sumOp = '+', currentOp = '+';
        
        int number = 0; 
        for(int idx = 0;idx < s.length(); idx++) {
            if(idx < (s.length()-1) && s.charAt(idx) == ' ') { 
                continue; 
            }
            
            char c = s.charAt(idx);
            if(Character.isDigit(c)) {
                number = number*10 + Character.getNumericValue(c); 
            } 
            
            if(idx == (s.length() -1) || c == '+' || c == '-' || c == '*' || c == '/'){ 
                if (currentOp == '+' || currentOp == '-') {
                    sumVal = (sumOp == '+')? sumVal + mulVal : sumVal - mulVal; 
                    mulVal = number; 
                    sumOp = currentOp;  // + or - 
                } else if (currentOp == '/') {
                    mulVal = mulVal/number; 
                } else if (currentOp == '*') {
                    mulVal = mulVal*number; 
                } 
                
                // reset next number & operator
                number = 0;
                currentOp = c; 
            } 
            
        }
        
        return (sumOp == '+')? sumVal + mulVal : sumVal - mulVal; 
    }
    

    }


Log in to reply
 

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