Java solution


  • 0
    S
        class Holder{
            int intVal;
            int xVal;
            public void addInt(int val){
                intVal += val;
            }
            public void addX(int val){
                xVal += val;
            }
            public String evaluate(Holder other){
                int xLeft = this.xVal-other.xVal;
                int right = other.intVal - this.intVal;
                if(xLeft==0){
                    if(right==0){
                        return "Infinite solutions";
                    }
                    else{
                        return "No solution";
                    }
                }
                right/=xLeft;
                return "x="+right;
            }
        }
        public String solveEquation(String equation) {
            String[] spl = equation.split("=");
            Holder left = evaluate(spl[0]);
            Holder right = evaluate(spl[1]);
            return left.evaluate(right);
        }
        Holder evaluate(String str){
            String[] split = str.split("(?=[+-])");
            Holder holder = new Holder();
            for(String val : split){
                char firstCh = val.charAt(0);
                if(firstCh=='+'){
                    val = val.substring(1);
                }
                if(val.contains("x")){
                    int xVal = val.length()==1?1:val.equals("-x")?-1:Integer.parseInt(val.substring(0, val.length()-1));
                    holder.addX(xVal);
                }
                else{
                    int intVal = Integer.parseInt(val);
                    holder.addInt(intVal);
                }
            }
            return holder;
        }
        
    }

Log in to reply
 

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