Share My C++ Solution


  • 0
    F
    class Solution {
    public:
        string solveEquation(string equation) {
            ///move sign handles the case when move an entry from right side of "=" to left, we need to flip the sign
            int xcount = 0, sum = 0, movesign = 1;
            for (int i = 0; i < equation.size();)
            {
                if (equation[i] == '=')
                {
                    movesign = -1;
                    ++ i;
                    continue;
                }
                int sign = 1, n = 0;
                if (equation[i] == '-')
                {
                    sign = -1;
                    ++i;
                }else if (equation[i] == '+')
                    ++i;
                if (i < equation.size() && equation[i] == 'x')
                    n = 1;
                else while(i < equation.size() && isdigit(equation[i]))
                    n = n*10 + equation[i ++] - '0';
                n *= sign * movesign ;
                if (i < equation.size() && equation[i] == 'x')
                {
                    xcount += n;
                    ++ i;
                }else
                    sum += n;
            }
            if (xcount == 0)
            {
                if (sum == 0)
                    return "Infinite solutions";
                else
                    return "No solution";
            }
            return "x=" + to_string(-sum / xcount);
        }
    };
    

Log in to reply
 

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