C++ O(n) AC Solution


  • 0
    class Solution {
    public:
        string solveEquation(string equation) {
            // coefficient of x, constant, sign, value of x
            int x = 0, n = 0, d = 0, sign = 1, res = 0;
            // is in left side of the equation, coefficient of x is one         
            bool left = true, one = true;
            for (char c : equation) {
                if (c == ' ') continue;
                if (isdigit(c)) {
                    one = false;
                    d = 10 * d + c - '0';
                    continue;
                }
                if (c == 'x') {
                    if (d == 0 && one) x += sign;
                    else x += sign * d;
                }
                else {
                    n += sign * d;
                    if (c == '-') sign = left ? -1 : 1;
                    else if (c == '+') sign = left ? 1 : - 1;
                    else { // right side of the equation
                        left = false;
                        sign = -1;
                    }
                }            
                one = true;
                d = 0;
            }
            n += sign * d;
            if (x == 0 && n == 0) return "Infinite solutions";
            if (x == 0) return "No solution";
            return "x=" + to_string(-1 * n / x);
        }
    };
    

Log in to reply
 

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