[LeetCode] Solve the Equation

640. Solve the Equation

Solve a given equation and return the value of ‘x’ in the form of a string “x=#value”. The equation contains only ‘+’, ‘-‘ operation, the variable ‘x’ and its coefficient. You should return “No solution” if there is no solution for the equation, or “Infinite solutions” if there are infinite solutions for the equation.

If there is exactly one solution for the equation, we ensure that the value of ‘x’ is an integer.

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
class Solution {
pair<int, int> normalize(string s) {
int x = 0, v = 0;
int d = 0;
int sign = s[0] == '-' ? -1 : 1;
for(int i = s[0] == '-' ? 1 : 0; i < s.length(); i++) {
if(isdigit(s[i])) d = d*10 + (s[i]&0b1111);
else if(s[i] == 'x') continue;
else if(s[i] == '-') {
bool isX = s[i-1] == 'x';
if(isX) x += max(d, (i >= 2 and s[i-2] == '0') ? 0 : 1)*sign;
else v += d * sign;
sign = -1;
d = 0;
} else if(s[i] == '+') {
bool isX = s[i-1] == 'x';
if(isX) x += max(d, (i >= 2 and s[i-2] == '0') ? 0 : 1)*sign;
else v += d * sign;
sign = 1;
d = 0;
}
}
bool isX = s.back() == 'x';
if(isX) x += max(d, (s.length() >= 2 and s[s.length() -2] == '0') ? 0 : 1)*sign;
else v += d * sign;
return {x,v};
}
public:
string solveEquation(string equation) {
auto pos = equation.find('=');
auto [lx, lv] = normalize(equation.substr(0,pos));
auto [rx, rv] = normalize(equation.substr(pos+1));
rv -= lv;
lx -= rx;
if(lx == 0 and rv == 0) return "Infinite solutions";
if(lx == 0 and rv != 0) return "No solution";
if(rv == 0) return "x=0";
return "x=" + to_string(rv/lx);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/solve-the-equation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.