"1+2*5/3+6/4*2" can anyone please tell the output to this?


  • 0
    S

    the expected answer is 6, can anyone explain how, since if we floor division outputs, we get 5 as the answer.


  • 0

    I get 6 for "1+2*5/3+6/4*2" with my code, check if your code logic is wrong.
    btw. 2*5/3 = 3, 6/4*2 = 2, thus 1+3+2=6
    my code is as followed :-)

    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()){
    	    		operator = s.charAt(i);
    	    		++i;
    	    	}
    	    	while(i < s.length() && Character.isLetterOrDigit(s.charAt(i))){
    	    		curVal = curVal*10 + (s.charAt(i) - '0');
    	    		++i;
    	    	}
    	    	if (operator == '+' || operator == '-') {	
    		        res += tempRes;// update res 
    		        tempRes = operator == '+' ? curVal : -curVal;     	
    		    } else if (operator == '*' || operator == '/') {
    		        tempRes = operator == '*' ? tempRes * curVal) : (tempRes / curVal); // not update res, keep loop
    		    }
    	    	
    	    }
    	    
    	    return res;
        }
    }

Log in to reply
 

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