640. 求解方程

代码实现(自解)
class Solution {
private:
void parse(string str, int& x, int& co) {
int pstr = 0;
int n = str.size();
bool flag = false;
string tmp = "";
int val = 0;
x = 0, co = 0;
while (pstr != n) {
if (str[pstr] == '-') {
flag = true;
pstr++;
}
else if (str[pstr] == '+') {
pstr++;
}
while (str[pstr] >= '0' && str[pstr] <= '9') {
tmp += str[pstr++];
}
if (str[pstr] == 'x') {
if (tmp == "") val = 1;
else val = stoi(tmp);
if (flag) x -= val;
else x += val;
}
else {
if (flag) co -= stoi(tmp);
else co += stoi(tmp);
pstr--;
}
pstr++;
flag = false;
tmp = "";
}
}
public:
string solveEquation(string equation) {
int equal = equation.find('=', 0);
string left = equation.substr(0, equal);
string right = equation.substr(equal + 1);
int x1, co1, x2, co2;
parse(left, x1, co1);
parse(right, x2, co2);
if (x1 == x2 && co1 == co2) return "Infinite solutions";
if (x1 == x2 && co1 != co2) return "No solution";
return "x=" + to_string((co2 - co1) / (x1 - x2));
}
};