class Solution {
public:
string solveEquation(string equation) {
int coe = 0, num = 0, i;
int flag = 1, tt = 1;
int cur = 0;
for(i = 0; i < equation.size(); i++)
{
if(equation[i] == '+'){
if(cur != 0)num += cur * flag * tt;
flag = 1;
cur = 0;
}
else if(equation[i] == '-'){
if(cur != 0)num += cur * flag * tt;
flag = -1;
cur = 0;
}
else if(equation[i] == '='){
if(cur != 0)num += cur * flag * tt;
tt = -1; flag = 1; cur = 0;
}
else if(equation[i] >= '0' && equation[i] <= '9'){
cur = cur * 10 + equation[i] - '0';
}
else if(equation[i] == 'x'){
if(i != 0 && equation[i - 1] == '0')continue;
else if(cur == 0)coe += flag * tt;
else coe += cur * flag * tt;
cur = 0;
}
}
if(cur != 0)num += cur * flag * tt;
if(coe == 0 && num == 0)return "Infinite solutions";
if(coe == 0 && num != 0)return "No solution";
int ans = -1 * num / coe;
char c[20];
sprintf(c, "%d", ans);
string ss = c;
return "x=" + ss;
}
};
640. Solve the Equation
最新推荐文章于 2024-08-23 09:59:49 发布