您的位置:首页 > 其它

Solve the Equation

2017-09-01 06:43 357 查看
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"


分成等号的左右两个部分,分别parse出未知数x前的系数,以及常数和, 然后计算

解析的过程中:

1. 碰到+ - 符号需要变号, 但是需要注意前面是常数的结束,需要结算 (如果是带有未知数的,则在第3步计算)

2. 遇到数字那就累加数字

3. 遇到x, 那么结算当前的x的系数,如果number != 0, 则说明有系数;如果 == 0 那么有两种可能 1. 如果x的index >0, 那么如果系数==0 则真的是==0,2. 如果x的index=0,那么默认系数就是1

代码:

class Solution {

class Wrap {
int numX;
int sumConstant;
Wrap(int numX, int sumConstant) {
this.numX = numX;
this.sumConstant = sumConstant;
}
}

public String solveEquation(String equation) {

String[] split = equation.split("=");
Wrap left = parse(split[0]);
Wrap right = parse(split[1]);
int xCount = left.numX - right.numX;
int constant = right.sumConstant - left.sumConstant;
if(xCount == 0 && constant == 0) return "Infinite solutions";
if(xCount == 0) return "No solution";

return "x=" + (constant/xCount);
}

private Wrap parse(String string) {

int numX = 0;
int sumConstant = 0;

int number = 0;
boolean positive = true;

for(int i=0;i<string.length();i++) {
char ch = string.charAt(i);
if(ch=='+' || ch=='-') {
if(number != 0) {
if(positive) {
sumConstant += number;
} else sumConstant -= number;
number = 0;
}
if(ch=='+'){
positive = true;
continue;
}
if(ch=='-') {
positive = false;
continue;
}
}

if(ch>='0' && ch<='9') {
number = number * 10 + (ch - '0');
} else if( ch == 'x') {
if((i>0 && number == 0 && string.charAt(i-1)!='0' ) || (number == 0 && i==0)) number = 1;
if(positive) {
numX += number;
} else numX -= number;
number = 0;
positive = true;
}
}
if(number != 0) {
if(positive) {
sumConstant += number;
} else sumConstant -= number;
}
return new Wrap(numX, sumConstant);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: