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”
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’.
- 我们最终是要把原方程式简化成 nx=k 的形式来检查是否有解
- 统计 n 时要加等号左侧的 x 的表达式, 比如+2x 我们就需要 n += 2, 等号右侧的表达式需要减, 比如+x 对应 n -= 1
- 统计 k 时与第 2 条相反, 等号左侧的减去, 等号右侧的加上
- 注意系数为 1 的情况,就是 x、+x、-x 的情况, 这些情况在解析的时候要单独处理
impl Solution {
pub fn solve_equation(equation: String) -> String {
let mut side = "left";
let mut var_count = 0;
let mut value = 0;
let mut buffer = String::new();
let mut parse = |mut buffer: String, side: &str| {
if buffer.is_empty() {
return;
}
if buffer.contains("x") {
buffer.pop();
let count = if buffer.is_empty() || buffer == "+" {
1
} else if buffer == "-" {
-1
} else {
buffer.parse::<i32>().unwrap()
};
if side == "left" {
var_count += count;
return;
}
var_count -= count;
return;
}
let val = buffer.parse::<i32>().unwrap();
if side == "right" {
value += val;
return;
}
value -= val;
};
for c in equation.chars() {
match c {
'=' => {
parse(buffer, side);
buffer = String::new();
side = "right"
}
'+' | '-' => {
parse(buffer, side);
buffer = String::new();
buffer.push(c);
}
_ => buffer.push(c),
}
}
if !buffer.is_empty() {
parse(buffer, side);
}
if var_count == 0 {
if value == 0 {
return "Infinite solutions".into();
}
return "No solution".into();
}
if value % var_count != 0 {
return "No solution".into();
}
format!("x={}", value / var_count)
}
}