您的位置:首页 > 其它

[leetcode]640. Solve the Equation

2017-07-24 19:47 411 查看
题目链接:https://leetcode.com/problems/solve-the-equation/#/description

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) {
// coef是合并同类项后的x系数
// con是常数项
// flag用来标识是在等号的左边还是右边,若是右边,则移项到左边,需要乘-1
long long coef = 0, con = 0, flag = 1;
reset();
for(int i=0;i<equation.size();i++) {
// 结算之前的数值,并与之前的系数合并
if(equation[i] == 'x') {
// 需要考虑单独为x时系数为1
coef += flag*sign*(cur==-1 ? 1 : cur);
isCoef = true;
}
else if(equation[i] == '+') {
// 若不是系数,则需要结算当前数值并合并到之前的常量中去
if(!isCoef) {
con += flag*cur*sign;
}
reset();
}
else if(equation[i] == '-') {
// 若不是系数,则需要结算当前数值并合并到之前的常量中去
// 这里需要额外考虑负号出现在第一个位置或者等号后面,此时不用结算数值
if(!isCoef && i>0 && equation[i-1] != '=') {
con += flag*cur*sign;
}
reset();
// 后续数值符号为-1
sign = -1;
}
else if(equation[i] == '=') {
if(!isCoef) {
con += flag*cur*sign;
}
reset();
// 开始遍历等号后的算式
flag = -1;
}
else {
// 对于数字字符,合并到cur
cur = (cur==-1 ? 0 : cur)*10 + (int)equation[i] - 48;
// 若最后一个字符是数字,则直接结算
if(i == equation.size()-1) {
con += flag*cur*sign;
}
}
}
if(coef==0) {
// 形如0x+con=0,若con等于0则有无穷个解,若con不为0,无解
if(con == 0)
return "Infinite solutions";
return "No solution";
}
// x = -con/coef
return "x=" + to_string(con*(-1)/coef);
}

private:
// cur是当前的数值,若紧接着的字符仍然是数字,则cur=cur*10+nextnumber
// sign是当前数值的符号,根据之前的正负号字符来设置
long long cur, sign;
// 判断当前数值是否是x的系数
bool isCoef;
// 每遇到+,-,=都需要reset一遍
void reset() {
cur = -1;
sign = 1;
isCoef = false;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: