程式語言 - LeetCode - CPP - 640. Solve the Equation



題目:


解答:

class Solution {
public:
    string solveEquation(string equation) {
        string s;
        int l = 1;
        int x = 0;
        int num = 0;
        int sign = 1;
        int n = equation.size();

        auto handle = [&]() {
            if (s.size() > 0) {
                if (s.back() == 'x') {
                    s.pop_back();

                    if (s.size() == 0) {
                        x += sign * l;
                    }
                    else {
                        x += stoi(s) * sign * l;
                    }
                }
                else {
                    num += stoi(s) * sign;
                }
            }

            s = "";
        };

        for (int i = 0; i < n; ++i) {
            char ch = equation[i];

            if (ch == '+') {
                handle();

                sign = 1;
            }
            else if (ch == '-') {
                handle();

                sign = -1;
            }
            else if (ch == '=') {
                handle();

                sign = 1;
                num *= -1;
                l = -1;
            }
            else {
                s += ch;
            }
        }

        handle();

        if (x != 0) {
            num /= x;
        }
        else {
            if (x == 0 && num == 0) {
                return "Infinite solutions";
            }
            else if (x == 0 && num != 0) {
                return "No solution";
            }
        }

        return "x=" + to_string(num);
    }
};