题目描述:
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) {
string left,right;
istringstream iss(equation);
getline(iss,left,'=');
getline(iss,right,'=');
int left_x=0, left_num=0, right_x=0, right_num=0;
helper(left,left_x,left_num);
helper(right,right_x,right_num);
int x=left_x-right_x;
int num=right_num-left_num;
if(x==0&&num!=0) return "No solution";
else if(x==0&&num==0) return "Infinite solutions";
else return "x="+to_string(num/x);
}
void helper(string equation, int& x, int& num) //根据加减号分割表达式,计算表达式中x的系数和常数
{
int i=0;
int j=0;
while(j<equation.size())
{
while(j!=equation.size()-1&&equation[j+1]!='+'&&equation[j+1]!='-') j++;
string s=equation.substr(i,j-i+1);
int sign=1;
if(s[0]=='-') sign=-1;
if(s[0]=='+'||s[0]=='-') s=s.substr(1);
if(s=="x") x+=sign; //当s=="x"时,不存在系数,所以要单独判断
else if(s.back()=='x') x+=sign*atoi(s.substr(0,s.size()-1).c_str());
else num+=sign*atoi(s.c_str());
j++;
i=j;
}
}
};
本文介绍了一种用于解析和求解代数方程的算法,该算法能够处理包含加减运算、变量及其系数的方程,并返回方程的解。通过多个实例展示了算法的有效性和准确性。
7888

被折叠的 条评论
为什么被折叠?



