Wednesday, May 1, 2019

LeetCode [640] Solve the Equation

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution
{
  public:
    void processString(string s, int & c, int& ce)
    {
        int i = 0, n = s.size(), sign = 1;
        while (i < n)
        {
            if (isdigit(s[i]))
            {
                int j = i;
                while (j < n && isdigit(s[j]))
                    j++;
                int val = stoi(s.substr(i, j - i));
                if (j < n && s[j] == 'x')
                {
                    ce += sign * val;
                    j++;
                }
                else
                {
                    c += sign * val;
                }
                i = j;
            }
            else if (s[i] == '+' || s[i] == '-')
            {
                sign = (s[i] == '+' ? 1 : -1);
                i++;
            }
            else if(s[i]=='x')
            {
                ce += sign;
                i++;
            }
        }
    }

    string solveEquation(string equation)
    {
        int e = equation.find_first_of('=');
        string l = equation.substr(0, e);
        string r = equation.substr(e + 1, equation.size() - e - 1);
        int cl = 0, cel = 0, cr = 0, cer = 0, c = 0, ce = 0;
        processString(l, cl, cel);
        processString(r, cr, cer);
        c = cl-cr; 
        ce = cer-cel;

        if(ce==0 && c!=0) return "No solution";
        if(ce==0 && c==0) return "Infinite solutions";
        return "x="+to_string(c/ce);
    }
};

No comments:

Post a Comment