# 640. Solve the Equation

Solve a given equation and return the value of `x` in the form of string “x=#value”. The equation contains only ‘+’, ‘-‘ operation, the variable `x` and its coefficient.

If there is no solution for the equation, return “No solution”.

If there are infinite solutions for the equation, return “Infinite solutions”.

If there is exactly one solution for the equation, we ensure that the value of `x` is an integer.

Example 1:

``````Input: "x+5-3+x=6+x-2"
Output: "x=2"
``````

Example 2:

``````Input: "x=x"
Output: "Infinite solutions"
``````

Example 3:

``````Input: "2x=x"
Output: "x=0"
``````

Example 4:

``````Input: "2x+3x-6x=x+2"
Output: "x=-1"
``````

Example 5:

``````Input: "x=x+2"
Output: "No solution"
``````

``````class Solution {
public:
string solveEquation(string equation) {
int a = 0, b = 0;
auto found = equation.find("=");
helper(equation.substr(0, found), true, a, b);
helper(equation.substr(found + 1), false, a, b);
if (a == 0 && a == b) return "Infinite solutions";
if (a == 0 && a != b) return "No solution";
return "x=" + to_string(b / a);
}
void helper(string e, bool isLeft, int& a, int& b) {
int sign = 1, num = -1;
e += "+";
for (int i = 0; i < e.size(); ++i) {
if (e[i] == '-' || e[i] == '+') {
num = (num == -1) ? 0 : (num * sign);
b += isLeft ? -num : num;
num = -1;
sign = (e[i] == '+') ? 1 : -1;
} else if (e[i] >= '0' && e[i] <= '9') {
if (num == -1) num = 0;
num = num * 10 + e[i] - '0';
} else if (e[i] == 'x') {
num = (num == -1) ? sign : (num * sign);
a += isLeft ? num : -num;
num = -1;
}
}
}
};
``````

``````class Solution {
public:
string solveEquation(string equation) {
int n = equation.size(), a = 0, b = 0, sign = 1, j = 0;
for (int i = 0; i < n; ++i) {
if (equation[i] == '+' || equation[i] == '-') {
if (i > j) b += stoi(equation.substr(j, i - j)) * sign;
j = i;
} else if (equation[i] == 'x') {
if (i == j || equation[i - 1] == '+') {
a += sign;
} else if (equation[i - 1] == '-') {
a -= sign;
} else {
a += stoi(equation.substr(j, i - j)) * sign;
}
j = i + 1;
} else if (equation[i] == '=') {
if (i > j) b += stoi(equation.substr(j, i - j)) * sign;
sign = -1;
j = i + 1;
}
}
if (j < n) b += stoi(equation.substr(j)) * sign;
if (a == 0 && a == b) return "Infinite solutions";
if (a == 0 && a != b) return "No solution";
return "x=" + to_string(-b / a);
}
};
``````

https://discuss.leetcode.com/topic/95203/concise-java-solution

https://discuss.leetcode.com/topic/95279/c-two-pointers-concise-solution

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation