求解一个给定的方程,将x以字符串 "x=#value" 的形式返回。该方程仅包含 '+' , '-' 操作,变量 x 和其对应系数。
如果方程没有解,请返回 "No solution" 。如果方程有无限解,则返回 “Infinite solutions” 。
题目保证,如果方程中只有一个解,则 'x' 的值是一个整数。
示例 1:
输入: equation = "x+5-3+x=6+x-2"
输出: "x=2"
示例 2:
输入: equation = "x=x"
输出: "Infinite solutions"
示例 3:
输入: equation = "2x=x"
输出: "x=0"
提示:
3 <= equation.length <= 1000
equation 只有一个 '='.
equation 方程由整数组成,其绝对值在 [0, 100] 范围内,不含前导零和变量 'x' 。
class Solution {
public String solveEquation(String equation) {
int factor = 0;
int val = 0;
int sign1 = 1;
int index = 0;
int n = equation.length();
while (index < n){
if (equation.charAt(index) == '='){
sign1 = -1;
index ++;
continue;
}
int sign2 = sign1;
if (index < n && equation.charAt(index) == '-'){
sign2 = -sign1;
index ++;
}else if (index < n && equation.charAt(index)== '+'){
index ++;
}
int number = 0;
boolean numberValid = false;
while (index < n && Character.isDigit(equation.charAt(index)) ){
number = number * 10 + (equation.charAt(index) - '0');
index ++;
numberValid = true;
}
if (sign2 == -1){
number = -number;
}
if (index < n && equation.charAt(index) == 'x'){
if (numberValid){
factor += number;
}else{
factor += sign2;
}
index ++;
}else {
val += number;
}
}
if (factor == 0){
if (val == 0){
return "Infinite solutions";
}else{
return "No solution";
}
}
if (-val%factor != 0) {
return "No solution";
}
return "x="+ (-val/factor);
}
}
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/solve-the-equation