0640. Solve the Equation
https://leetcode.com/problems/solve-the-equation
Description
Solve a given equation and return the value of 'x'
in the form of a string "x=#value"
. The equation contains only '+'
, '-'
operation, the variable 'x'
and its coefficient. You should return "No solution"
if there is no solution for the equation, or "Infinite solutions"
if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of 'x'
is an integer.
Example 1:
**Input:** equation = "x+5-3+x=6+x-2"
**Output:** "x=2"
Example 2:
**Input:** equation = "x=x"
**Output:** "Infinite solutions"
Example 3:
**Input:** equation = "2x=x"
**Output:** "x=0"
Example 4:
**Input:** equation = "2x+3x-6x=x+2"
**Output:** "x=-1"
Example 5:
**Input:** equation = "x=x+2"
**Output:** "No solution"
Constraints:
3 <= equation.length <= 1000
equation
has exactly one'='
.equation
consists of integers with an absolute value in the range[0, 100]
without any leading zeros, and the variable'x'
.
ac
class Solution {
public String solveEquation(String equation) {
String[] strs = equation.split("=");
int[] l = extract(strs[0]);
int[] r = extract(strs[1]);
int right = r[0] - l[0];
int left = l[1] - r[1];
if (left == 0 && right == 0) {
return "Infinite solutions";
} else if (left == 0 && right != 0) {
return "No solution";
} else {
return "x=" + (int)(right / left);
}
}
public int[] extract(String s) {
String[] strs = s.split("-");
int val = 0, xval = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i].length() == 0) continue; // skip empty
String[] vals = strs[i].split("\\+");
for (int j = 0; j < vals.length; j++) {
int sign = i != 0 && j == 0 ? -1 : 1;
if (vals[j].indexOf("x") < 0) { // normal value
val += sign * Integer.parseInt(vals[j]);
} else if ("x".equals(vals[j])) {
xval += sign * 1;
} else {
xval += sign * Integer.parseInt(vals[j].replace("x", ""));
}
}
}
return new int[]{val, xval};
}
}
/*
1) extract the formula, return {normalVal, x-val}; 2) judge left part and right part
*/
Last updated
Was this helpful?