Simple Java Solution


  • 0
    public class Solution {
        public int calculate(String s) {
            if (s == null) return 0;
    	    s = "+" + s.trim().replaceAll(" ", "") + "+0";// replace space and use "+"/"+0" to mark as start/end
        
    	    int res = 0; 
    	    long tempRes = 0;
    	    char operator = '+';
    	    
    	    int i = 0;
    	    while(i < s.length()){
    	    	long curVal=0;
    	    	if(i < s.length()){//get operator
    	    		operator = s.charAt(i);
    	    		++i;
    	    	}
    	    	while(i < s.length() && Character.isLetterOrDigit(s.charAt(i))){//get digit
    	    		curVal = curVal*10 + (s.charAt(i) - '0');
    	    		++i;
    	    	}
    	    	if (operator == '+' || operator == '-') {//update result	
    		        res += tempRes; 
    		        tempRes = operator == '+' ? curVal : -curVal;
    		    } else if (operator == '*' || operator == '/') {//not update result
    		        tempRes = operator == '*' ? (tempRes * curVal) : (tempRes / curVal); //keep loop
    		    }
    	    }   
    	    return res;
        }
    }

Log in to reply
 

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