-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolvetheEquation.cpp
More file actions
40 lines (38 loc) · 1.22 KB
/
solvetheEquation.cpp
File metadata and controls
40 lines (38 loc) · 1.22 KB
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
// Source: https://leetcode.com/problems/solve-the-equation/
// Author: Miao Zhang
// Date: 2021-02-25
class Solution {
public:
string solveEquation(string equation) {
auto parse = [](string_view s) -> vector<int> {
int a{0}, b{0};
int sign = 1;
long num = 0;
bool digit = false;
for (char c: s) {
if (isdigit(c)) {
digit = true;
num = num * 10 + c - '0';
} else {
if (c == 'x') {
a += (digit ? num : 1) * sign;
} else {
b += num * sign;
sign = c == '+' ? 1: -1;
}
digit = false;
num = 0;
}
}
b += num * sign;
return {a, b};
};
auto pos = equation.find('=');
auto l = parse(string_view(equation).substr(0, pos));
auto r = parse(string_view(equation).substr(pos + 1));
l[0] -= r[0];
r[1] -= l[1];
if (l[0] == 0) return r[1] == 0 ? "Infinite solutions" : "No solution";
return "x=" + to_string(r[1] / l[0]);
}
};