Solve a given equation and return the value ofx
in the form of string "x=#value". The equation contains only '+', '-' operation, the variablex
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 ofx
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"
Tips:
注意符号,别搞反了。
Code:
public class Solution {
public String solveEquation(String equation) {
String[] eqs = equation.split("=");
int countX_L = 0, countX_R = 0;
int num_L = 0, num_R = 0;
String[] left = eqs[0].split("(?=[-+])");
String[] right = eqs[1].split("(?=[-+])");
for (String s : left) {
if (s.equals("+x") || s.equals("x")) countX_L++;
else if (s.equals("-x")) countX_L--;
else if (s.contains("x")) countX_L += Integer.valueOf(s.substring(0, s.indexOf("x")));
else num_L += Integer.valueOf(s);
}
for (String s : right) {
if (s.equals("+x") || s.equals("x")) countX_R++;
else if (s.equals("-x")) countX_R--;
else if (s.contains("x")) countX_R += Integer.valueOf(s.substring(0, s.indexOf("x")));
else num_R += Integer.valueOf(s);
}
if (countX_L == countX_R && num_L == num_R) return "Infinite solutions";
if (countX_L == countX_R) return "No solution";
return "x=" + (num_R - num_L) / (countX_L - countX_R);
}
}