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"
Approach
- 这道题题目大意很明显就是解方程式,难点主要是该怎么提取有用的字符串,然后进行处理,对这个问题我习惯性分类讨论,就是到哪个字符应该有什么样的操作,这里有四个关键字符,就是
+ - x =
,不难发现这四个字符是有效数字的结尾,所以我们可以直接进行判断运算即可,看代码会更加容易理解。
Code
class Solution {
public:
void helper(bool &flag,bool &turn,string &str,int &x,int &con) {
if (turn) {
if (str[0] == '-') str = str.substr(1);
else str = '-' + str;
}
if (flag) x += stoi(str);
else con += stoi(str);
str.clear();
flag = false;
}
string solveEquation(string equation) {
int x = 0, con = 0, len = equation.size();
bool turn = false,flag=false;
string str = "";
for (int i = 0; i < len; i++) {
if (equation[i] == '=') {
helper(flag, turn, str, x, con);
turn = true;
}
else if (equation[i] == '+') {
helper(flag, turn, str, x, con);
}
else if (equation[i] == '-') {
if (i!=0&&equation[i - 1] != '=') {
helper(flag, turn, str, x, con);
}
str="-";
}
else if (equation[i] == 'x') {
if (str == ""||str=="-")str += '1';
flag = true;
}
else
{
str += equation[i];
}
}
helper(flag, turn, str, x, con);
if (x == 0 && con == 0)return "Infinite solutions";
if (x == 0)return "No solution";
if (con == 0)return "x=0";
return "x=" + to_string(-con / x);
}
};