Java Solution with Some Explanations


  • 0

    My way:

    1. Split the equation by "=".
    2. Simply the left hand side and right hand side into ax + b and cx + d.
      i. Play a small trick when parse the LHS or RHS, check if the character at index 0 is a number or not, if it is, add "+" so that you can read the sign of the first number directly after splitting it by "[+-]".
      ii. Use a list to store all the signs.
    3. Combine the two sides into ax = b and discuss different conditions.
    public String solveEquation(String equation) {
        String[] lr = equation.split("=");
        int[] left_res = oneSide(lr[0]);
        int[] right_res = oneSide(lr[1]);
        int x_count = left_res[0] - right_res[0];
        int val = right_res[1] - left_res[1];
        if (x_count == 0) {
            if (val == 0)
                return "Infinite solutions";
            else return "No solution";
        }
        else{
            return "x=" + val/x_count;
        }
    }
    private int[] oneSide (String str) {
        int[] ret = new int[2]; 
        if (str.charAt(0) != '+' && str.charAt(0) != '-') {
            str = "+" + str;
        }
        List<Character> signs = new ArrayList<>();
        for (int i = 0; i<str.length(); i++) {
            if (str.charAt(i) == '+' || str.charAt(i) == '-') {
                signs.add(str.charAt(i));
            }
        }
        String[] valueAndVar = str.split("[+-]");
        for (int i = 1; i< valueAndVar.length; i++) {
            int sign = 1;
            int len = valueAndVar[i].length();
            if(signs.get(i-1)=='-') sign = -1;
            if ( valueAndVar[i].charAt(len-1) == 'x'){
                if (len == 1) {
                    ret[0] += sign*1;
                }
                else {
                    ret[0] += sign*Integer.parseInt(valueAndVar[i].substring(0,len-1));    
                }
            }
            else {
                ret[1] += sign*Integer.parseInt(valueAndVar[i]);
            }
        }
        return ret;
    }

Log in to reply
 

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