redundancy code, but short running time(beats 95%)


  • 0
    D
    public String solveEquation(String equation) {
        boolean left = true;
        int cX = 0;
        int cNum = 0;
        char operator = '+';
        int tmp = 0;
        for(int i = 0;i < equation.length();i++){
            char chr = equation.charAt(i);
            if(chr == '=') {
                cNum += operator=='+'? tmp:-tmp;
                tmp = 0;
                left = false;
                operator = '+';
            }
            else if(chr == '-' || chr == '+'){
                if(left)cNum += operator=='+'? tmp:-tmp;
                else cNum += operator=='+'? -tmp:tmp;
                tmp = 0;
                operator = chr;
            }
            else if(chr == 'x') {
                if(i!= 0 && equation.charAt(i-1) == '0') continue;                    
                   else if(tmp == 0){
                       if(left)cX += operator=='+' ? 1:-1;
                       else cX += operator=='+' ? -1:1;
                   }
                   else {
                       if(left)cX += operator=='+' ? tmp:-tmp;
                       else cX += operator=='+' ? -tmp:tmp;
                   }
                tmp = 0;
            }
            else{
                   tmp = tmp*10+(chr-'0');
            }   
        }
        cNum += operator=='+'? -tmp:tmp;
        if(cX == 0 && cNum == 0) return "Infinite solutions";
        if(cX == 0) return "No solution";
        int res = -cNum/cX;
        return "x="+res;
        
    }
    

    }


Log in to reply
 

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