题目:
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"
思路:
我们以等号为界,将方程分为左右两部分,并且分别计算出x的系数以及常数。最后合并同类项,并根据最终的系数和常数返回结果:如果系数为0,若常数也为0则有无穷多解,否则就无解。如果系数不为0,则返回常数除以系数即可。
实现中最麻烦的当属处理"+x", "-x", "+0x", "-0x"以及"x..."等情况。具体可见下面的代码中如何实现。
代码:
class Solution {
public:
string solveEquation(string equation) {
int index = equation.find_first_of('=');
int left_coe = 0, left_con = 0;
getValues(equation.substr(0, index), left_coe, left_con);
int right_coe = 0, right_con = 0;
getValues(equation.substr(index + 1), right_coe, right_con);
int coefficient = left_coe - right_coe;
int constant = right_con - left_con;
if (coefficient == 0) {
return constant == 0 ? "Infinite solutions" : "No solution";
}
else {
return "x=" + to_string(constant / coefficient);
}
}
private:
void getValues(string s, int &coefficient, int &constant) {
int value = 0, sign = 1;
for (int i = 0; i < s.length(); ++i) {
if (isdigit(s[i])) {
value = 10 * value + s[i] -'0';
}
else if (s[i] == '+') {
constant += value * sign;
value = 0, sign = 1;
}
else if (s[i] == '-') {
constant += value * sign;
value = 0, sign = -1;
}
else if (s[i] == 'x') {
if (i > 0 && (s[i - 1] == '+' || s[i - 1] == '-')) {
value = 1; // "+x" or "-x"
}
if (i == 0) { // "x" is the leading
value = 1;
}
coefficient += value * sign;
value = 0, sign = 1;
}
}
if (s.back() != 'x') {
constant += value * sign;
}
}
};