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)
}
}

这是一个关于解决含有变量x的一元线性方程的问题,方程式中仅包含加法和减法操作。程序首先将方程式简化为nx=k的形式,然后判断是否存在唯一解、无穷解或无解。如果n(x的系数)为0且k(常数项)也为0,则方程有无穷解;如果n不等于0,k能被n整除,则方程有一个整数解;否则,方程无解。
7874

被折叠的 条评论
为什么被折叠?



