C++ straight-forward 3ms solution


  • 0
    M
        string solveEquation(string equation) {
            int x1=0, x2=0, val1=0, val2=0, i=0;
            equation.append(1, '=');
            cal(x1, val1, i, equation);
            cal(x2, val2, ++i, equation);
            int res=val2-val1, x=x1-x2; 
            if(x==0&&res!=0) return "No solution";
            else if(x==0&&res==0) return "Infinite solutions";
            else return "x="+to_string(res/x);
        }
        
        void cal(int& x, int& v, int& i, string equation) {
            string s;
            for(i;equation[i]!='=';i++) {
                if((equation[i]=='+'||equation[i]=='-')&&s.size()!=0) {
                    if(s.back()=='x') {
                        s.pop_back();
                        if(s.size()==0||!isdigit(s.back())) s.append(1, '1');
                        x+=stoi(s);
                    }
                    else v+=stoi(s);
                    s.clear();
                }
                s.append(1, equation[i]);
            } 
            if(s.back()=='x') {
                s.pop_back();
                if(s.size()==0||!isdigit(s.back())) s.append(1, '1');
                x+=stoi(s);
            }
            else v+=stoi(s);
        }

Log in to reply
 

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