640.求解方程

This commit is contained in:
游由 2022-08-09 18:17:30 +08:00
parent 80aae26c97
commit f1d65b92f1
2 changed files with 91 additions and 0 deletions

View File

@ -136,6 +136,7 @@ mod q0623;
mod q0628;
mod q0633;
mod q0636;
mod q0640;
mod q0643;
mod q0674;
mod q0684;

View File

@ -0,0 +1,90 @@
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)
}
}
}
#[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());
}
}