Java no stack with two num variable beats 80%


  • 0
    C
    public class Solution {
    
        public int calculate(String s) {
    
            int num = 0;
            int num2 = 0;
            int sum = 0;
            int sign = 1;
            int op = 0;
            for(int i = 0; i<s.length(); i++) {
                if(s.charAt(i) == ' ')
                    continue;
                if(Character.isDigit(s.charAt(i))) {
                    num = num * 10 + Character.getNumericValue(s.charAt(i));
                }
                else{
                    if(op != 0) { //if previous operator is * or / calculate the result involves num2 and num and assign the value to num
                        if(op == 1) {
                            num *= num2;
                            num2 = 0;
                        }
                        else{
                            num = num2/num;
                            num2 = 0;
                        }
                    }
                    op = 0; 
                    if(s.charAt(i) == '+' || s.charAt(i) == '-') { // if current operator is + or -, add the current num to result
                        sum += sign * num;
                        sign = s.charAt(i) == '+'? 1:-1;
                    }
                    else{
                        num2 = num;
                        op = s.charAt(i) == '*'?1:-1;
                            
                    }
                    num = 0;
                }
            }
            if(op != 0) { //handle the last num
                if(op == 1) {
                    num *= num2;
                }
                else{
                    num = num2/num;
                }
            }
            sum += sign * num;
            return sum;
        }
    }

Log in to reply
 

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