Share my c# solution


  • 0
    T
    public class Solution {
        public string SolveEquation(string equation) {
            
            int countX = 0;
            int countV = 0;
            
            int sign = 1;
            int psign = 1;
            int n = 0;
            equation = equation+"-";
            bool startWith0 = false;
            int len = equation.Length;
            for(int i = 0;i<len;i++){
                if(equation[i] == '+'){
                    n *= sign*psign;
                    if(i>0 && equation[i-1] =='x'){
                        countX+=n;
                    }else{
                        countV+=n;
                    }
                    sign = 1;
                    n=0;
                }else if(equation[i] == '-'){
                    n *= sign*psign;
                    if(i>0 && equation[i-1] =='x'){
                        countX+=n;
                    }else{
                        countV+=n;
                    }
                    sign = -1;
                    n=0;
                }else if(equation[i] == '='){
                    n *= sign*psign;
                    if(i>0 && equation[i-1] =='x'){
                        countX+=n;
                    }else{
                        countV+=n;
                    }
                    sign = 1;
                    psign=-1;
                    n=0;
                }else if(equation[i] != 'x' ){
                    n=n*10+(equation[i]-'0');
                }else if(n == 0 && (i ==0 || equation[i-1] == '+' || equation[i-1] == '-' || equation[i-1] == '=')){
                        n = 1;
                }
                //Console.WriteLine(countX+","+countV+","+n);
            }
            
            countV = -countV;
            
            if(countX == 0 && countV == 0){
                return "Infinite solutions";
            }else if(countX == 0  && countV != 0){
                return "No solution";
            }else{
                return "x="+(countV/countX);
            }
            
        }
    }
    

Log in to reply
 

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