-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path640.cpp
94 lines (91 loc) · 3 KB
/
640.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
__________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
string solveEquation(string equation) {
// ax + b = 0
int a = 0, b = 0, coef;
bool sign = true, on_right = false;
int i = 0;
while (i < equation.size()) {
if (equation[i] == 'x') {
a += (2 * sign - 1) * (1 - 2 * on_right);
++i;
} else if (equation[i] == '+' || equation[i] == '-') {
sign = equation[i] == '+' ? true : false;
++i;
} else if (equation[i] == '=') {
on_right = true;
sign = true;
++i;
} else {
tie(coef, i) = readCoef(equation, i);
if (i < equation.size() && equation[i] == 'x') {
a += (2 * sign - 1) * (1 - 2 * on_right) * coef;
++i;
} else {
b += (2 * sign - 1) * (1 - 2 * on_right) * coef;
}
}
}
// ax + b = 0
if (a == 0 && b == 0) {
return "Infinite solutions";
} else if (a == 0 && b != 0) {
return "No solution";
} else {
return "x=" + to_string(-b / a);
}
}
private:
tuple<int, int> readCoef(const string & equation, const int i) {
int j = i + 1;
while (j < equation.size() && isdigit(equation[j])) {
++j;
}
return {stoi(equation.substr(i, j - i)), j};
}
};
__________________________________________________________________________________________________
sample 8488 kb submission
class Solution {
public:
string solveEquation(string equation) {
int sign = 1, coeff = 0, num = 0, flag = 1, sum = 0;
for (int i = 0; i < equation.size(); i++) {
char c = equation[i];
if (c == '=') {
if (num != 0) {
sum += flag*sign*num;
num = 0;
sign = 1;
}
flag = -1;
}
if (isdigit(c)) {
num = num*10 + c - '0';
}
if (c == 'x') {
if (num == 0 && (i == 0 || !isdigit(equation[i-1]))) {
num = 1;
}
coeff += flag*sign*num;
num = 0;
sign = 1;
}
if (c == '+' || c == '-' || i == equation.size()-1) {
sum += flag*sign*num;
num = 0;
sign = c == '+' ? 1 : -1;
}
}
if (coeff == 0 && sum == 0) {
return "Infinite solutions";
} else if (coeff == 0 && sum != 0) {
return "No solution";
} else {
return "x=" + to_string(-sum/coeff);
}
}
};
__________________________________________________________________________________________________