Very simple Java solution with full comments


  • 2
    /*
    * Algorithm:
    * split the equation to two side
    *
    * try all x from -1000 to 1000 and calc value of each side
    *
    * if result of two side is equal, then totalAnswer increase
    *
    * if totalAnswer == 0 mean No solution
    * if totalAnswer > 1 mean Infinite solutions
    * if totalAnswer == 1 mean we have only one answer
    * */
    public String solveEquation(String equation) {
        // split equation to two side
        String[] side = equation.split("=");
    
        // define totalAnswer and lastAnswer
        int totalAnswer = 0;
        int lastAnswer = 0;
    
        // try all x from -1000 to 1000
        for (int x = -1000; x <= 1000; x++) {
            if (calc(x, side[0]) == calc(x, side[1])) {
                totalAnswer++;
                lastAnswer = x;
            }
        }
    
        if (totalAnswer == 0) {
            return "No solution";
        }
    
        if (totalAnswer > 1) {
            return "Infinite solutions";
        }
    
        return "x=" + lastAnswer;
    }
    
    private long calc(int x, String s) {
        long answer = 0;
        int idx = 0;
        char c = '+';
        boolean haveBefore;
    
        while (idx < s.length()) {
            long val = 0;
            haveBefore = false;
            
            // try to parse string to int
            // example: "21" to 21, "2x" to 2 * x, "x" to x
            while (idx < s.length() && !"+-".contains(s.charAt(idx) + "")) {
                if (s.charAt(idx) != 'x') {
                    val *= 10;
                    val += s.charAt(idx) - '0';
                    haveBefore = true;
                } else {
                    if (haveBefore) {
                        val *= x;
                    } else {
                        val = x;
                    }
                }
                idx++;
            }
            
            // sum val to final answer
            if (c == '+') {
                answer += val;
            } else {
                answer -= val;
            }
    
            if (idx < s.length()) {
                c = s.charAt(idx);
                idx++;
            }
        }
    
        return answer;
    }
    

Log in to reply
 

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