您的位置:首页 > 其它

Solve the Equation问题及解法

2017-10-19 10:34 507 查看
问题描述:

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.:

示例:

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

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

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

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

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


问题分析:

将等式分解,左边未知数,右边常量,按照一元一次方程组的求解方法求解。

过程详见代码:

class Solution {
public:
string solveEquation(string equation) {
int lx = 0,rx = 0;
int lv = 0, rv = 0;
int t = 0, sign = 1, flag = 0;
for (int i = 0; i < equation.length(); i++)
{
if (!flag)
{
if (equation[i] == '-' || equation[i] == '+' || equation[i] == '=')
{
if (i > 0 && equation[i - 1] != 'x') lv += t* sign;
if (equation[i] == '-') sign = -1;
else if (equation[i] == '+')sign = 1;
else
{
flag = 1;
sign = 1;
}
t = 0;
}
else if (equation[i] == 'x')
{
if (!i || (equation[i - 1] < '0' || equation[i - 1] > '9')) t = 1;
lx += sign * t;
t = 0;
}
else t = t * 10 + equation[i] - '0';
}
else
{
if (equation[i] == '-' || equation[i] == '+')
{
if (i > 0 && equation[i - 1] != 'x') rv += t* sign;
if (equation[i] == '-') sign = -1;
else sign = 1;
t = 0;
}
else if (equation[i] == 'x')
{
if (!i || (equation[i - 1] < '0' || equation[i - 1] > '9')) t = 1;
rx += sign * t;
t = 0;
}
else t = t * 10 + equation[i] - '0';
}
}
if (equation.back() != 'x') rv += t* sign;
lx -= rx;
rv -= lv;

if (lx == 0 && rv == 0) return "Infinite solutions";
else if (lx != 0) return "x=" + to_string(rv / lx);
else return "No solution";
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: