-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0640.cpp
More file actions
34 lines (30 loc) · 1021 Bytes
/
Copy path0640.cpp
File metadata and controls
34 lines (30 loc) · 1021 Bytes
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
class Solution {
static pair<int, int> count(const string_view &s) {
int x = 0, nums = 0, sign = 1;
for (int i = 0; i < size(s); i++) {
if (s[i] == '+')
sign = 1;
else if (s[i] == '-')
sign = -1;
else {
int num = s[i] == 'x' ? 1 : 0;
while (isdigit(s[i]))
num = num * 10 + s[i++] - '0';
if (s[i] == 'x')
x += sign * num;
else
nums += sign * num, i--;
}
}
return {x, nums};
}
public:
string solveEquation(const string &equation) const {
const string_view sv(equation);
const auto it = sv.find('=');
const auto [lx, ln] = count({begin(sv), it});
const auto [rx, rn] = count(sv.substr(it + 1));
if (lx == rx) return ln == rn ? "Infinite solutions" : "No solution";
return "x=" + to_string((rn - ln) / (lx - rx));
}
};