您的位置:首页 > 其它

Math-640-Solve the Equation

2018-01-29 17:03 429 查看
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"


Best Solution:

class Solution {
public String solveEquation(String equation) {
if(equation == null || equation.length() == 0) return "No solution";
String[] sides = equation.split("=");
int[] left = parse(sides[0]), right = parse(sides[1]);
if(left[0] == right[0]) {
if(left[1] == right[1]) return "Infinite solutions";
return "No solution";
}
int val = (right[1]-left[1])/(left[0]-right[0]);
return "x="+val;
}

private int[] parse(String s) {
int sign = 1, val = 0;
int[] res = new int[2];
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if(c=='x') {
if(i == 0) res[0]++;
else if(s.charAt(i-1) == '-' || s.charAt(i-1) == '+') res[0] += sign;
else res[0] += sign * val;
val = 0;
} else if(c == '-' || c == '+') {
res[1] += sign * val;
val = 0;
sign = c == '-' ? -1 : 1;
} else {
val = val * 10 + c - '0';
}
}
res[1] += sign * val;
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: