my_leetcode/rust/src/implements/q0640.rs

102 lines
3.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::fmt::format;
use crate::Solution;
impl Solution {
/// [640.求解方程](https://leetcode.cn/problems/solve-the-equation/)
///
/// 2022-08-09 14:19:01
///
/// 求解一个给定的方程,将`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'` 。
/// + Related Topics
/// * 数学
/// * 字符串
/// * 模拟
pub fn solve_equation(equation: String) -> String {
/*let (mut a,mut b,mut c) = (0, 0, 0);
let mut sign = 1;
let mut left = 1;
let mut has_c = false;
for z in equation.into_bytes() {
match z {
b'x' => {
a += if has_c { sign * left * c } else { sign * left };
c = 0;
has_c = false;
}
b'+' => {
b += sign * left * c;
c = 0;
sign = 1;
has_c = false;
}
b'-' => {
b += sign * left * c;
c = 0;
sign = -1;
has_c = false;
}
b'=' => {
b += sign * left * c;
c = 0;
sign = 1;
left = -1;
has_c = false;
}
_ => {
c = c * 10 + (z - b'0') as i32;
has_c = true;
}
}
}
b += sign * left * c;
match (a, b) {
(0, 0) => "Infinite solutions".to_owned(),
(0, _) => "No solution".to_owned(),
_ => format!("x={}", -b / a)
}*/
match equation.into_bytes().into_iter().fold((0, 0, 0, 1, 1, false), |(a, b, c, sign, left, has_c), z| match z {
b'x' => (a + if has_c { sign * left * c } else { sign * left }, b, 0, sign, left, false),
b'+' => (a, b + sign * left * c, 0, 1, left, false),
b'-' => (a, b + sign * left * c, 0, -1, left, false),
b'=' => (a, b + sign * left * c, 0, 1, -1, false),
_ => (a, b, c * 10 + (z - b'0') as i32, sign, left, true)
}) {
(a, b, c, sign, left, _) => match (a, b + sign * left * c) {
(a, b) => if a == 0 { if b == 0 { "Infinite solutions".to_owned() } else { "No solution".to_owned() } } else { format!("x={}", -b / a) }
}
}
}
}
#[cfg(test)]
mod test {
use crate::Solution;
#[test]
fn test_q0640() {
assert_eq!(Solution::solve_equation("x+5-3+x=6+x-2".to_owned()), "x=2".to_owned());
assert_eq!(Solution::solve_equation("x=x".to_owned()), "Infinite solutions".to_owned());
assert_eq!(Solution::solve_equation("2x=x".to_owned()), "x=0".to_owned());
assert_eq!(Solution::solve_equation("0x=0".to_owned()), "Infinite solutions".to_owned());
assert_eq!(Solution::solve_equation("0=0x".to_owned()), "Infinite solutions".to_owned());
}
}