Java Simple, AC (100 %) Solution


  • 0
    public class Expr {
        private int xw;        // weight of x-coeff
        private int cw;        // weight of constants
            
        public Expr (String str) {
            int sign = 1;
            Integer num = null;
            for (int idx = 0; idx < str.length(); idx ++) {
                char ch = str.charAt (idx);
                if (ch >= '0' && ch <= '9') {
                    if (num == null) num = 0;
                    num = 10 * num + (ch - '0');
                } else if (ch == 'x') {
                    xw += sign * (num == null ? 1 : num);
                    num = null;
                } else {
                    if (num != null) cw += sign * num;
                    sign = ch == '+' ? 1 : -1;
                    num = null;
                }
            }
                if (num != null) cw += sign * num;
        }
    }
        
    public String solveEquation(String equation) {
        Expr l = new Expr (equation.split ("=") [0]);
        Expr r = new Expr (equation.split ("=") [1]);
            
        if (l.xw == r.xw && l.cw == r.cw) return "Infinite solutions";
        l.xw -= r.xw; l.cw -= r.cw;
            
        if (l.xw == 0) return "No solution";
        return "x=" + (-(l.cw/l.xw));        
    }
    
    

Log in to reply
 

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