JavaScript Solution


  • 0
    N

    It is a JavaScript implementation of https://discuss.leetcode.com/topic/95203/concise-java-solution

    var solveEquation = function(equation) {    
        var res = evaluateExpression(equation.split("=")[0]);
        var res2 = evaluateExpression(equation.split("=")[1]);    
        res[0] -= res2[0]; //left side equation
        res[1] = res2[1] - res[1]; //right side equation   
        if(res[0] === 0 && res[1] === 0) {
           return "Infinite solutions";
        } else if(res[0] === 0) {
           return "No solution";       
        } else {
            return "x=" + Math.floor(parseInt(res[1]/res[0]));       
        }
    };
    
    function evaluateExpression(exp) {
        var tokens = exp.split(/(?=[-+])/);
        var res = new Array(2).fill(0);
        for(var i = 0; i < tokens.length; i++) {
           var token =  tokens[i];
           if(token === '+x' || token === 'x') {
              res[0] += 1;
            } else if(token === '-x') {
              res[0] -= 1;        
            }  else if(token.includes("x")){ 
              res[0] += parseInt(token.substring(0, token.indexOf("x")));         
            } else {
              res[1] += parseInt(token);         
            }
        }
        return res;
    }
    

Log in to reply
 

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