C++ Easy 3ms solution


  • 0
    M

    I checked the 0ms solution, but don't have idea what is the difference. Any hint? thanks in advance

    class Solution {
    public:
        static const int debug = 0;
        string solveEquation(string equation) {
            if (debug) cout << equation << endl;
            // ax + b = 0
            int a = 0, b = 0;
            int lr = 1; // 1 for left-hand, -1 for right hand
            int op = 1; // 1 for +, -1 for -
            for (int ks=0, ke=0; ke!=equation.length()+1; ++ke){
                if (ke==equation.length() || equation[ke]=='+' || equation[ke]=='-' || equation[ke]=='='){
                    // end of last token
                    if (ke>ks) { // not empty token
                        if (debug) cout << equation.substr(ks, ke-ks) << "\t";
                        int number;
                        if (equation[ke-1]=='x'){
                            // is x token
                            number = ke-1-ks>0 ? atoi(equation.substr(ks,ke-1-ks).c_str()) : 1;
                            a += lr * op * number;
                        }else{
                            // is number token
                            number = ke-ks>0 ? atoi(equation.substr(ks,ke-ks).c_str()) : 1;
                            b += lr * op * number;
                        }                    
                        if (debug) cout << lr*op*number << endl;
                    }
    
                    // prepare for next
                    if (ke==equation.length()) break;
                    ks = ke + 1;
                    equation[ke]=='=' ? lr*=-1, op=1 : 0;
                    equation[ke]=='+' ? op=1 : 0;
                    equation[ke]=='-' ? op=-1 : 0;
                }
            }
            // solution
            string sol("x=");
            if (a==0 && b==0) sol = "Infinite solutions";
            else if (a==0 && b!=0) sol = "No solution";
            else sol += to_string(-b/a);
            return sol;
        }
    };
    

Log in to reply
 

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