Java Solution, No regrex


  • 0
    M

    General idea:
    Use a coeff variable to record the final x coefficients
    Use a val variable to record the final numbers left

    Corner case such as x coefficient being 0 need to be taken care.

      public String solveEquation(String equation) {
            int coeff =0, sign =1, i=0, plus=1, val=0;
            while(i< equation.length()){
                if(equation.charAt(i)=='+'){
                    plus=1;
                    i++;
                }else if(equation.charAt(i)=='-'){
                    plus=-1;
                    i++;
                }else if(equation.charAt(i)=='=') {
                    sign=-1;
                    plus=1;
                    i++;
                }else{
                    int num=0,length=0;
                    while(i<equation.length() && Character.isDigit(equation.charAt(i))){
                        num = num*10+(equation.charAt(i)-'0');
                        i++;
                        length++;
                    }
                    if(i==equation.length()){
                        val += sign*num*plus;
                    }else if(equation.charAt(i)=='x'){
                        if(num==0){
                            int add = (length==0?plus*sign:0);
                            coeff+= add;
                        }else{
                            coeff+= num*plus*sign;
                        }
                        i++;
                    }else{
                        val+= sign*num*plus;
                    }
                }
            }
            
            if(coeff!=0 && val==0) return "x=0";
            if(coeff==0 && val!=0) return "No solution";
            if(coeff==0 && val==0) return "Infinite solutions";
            return "x="+String.valueOf(-val/coeff);
            
        }
    

Log in to reply
 

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