LeetCode/rs/complex-number-multiplication.rs
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

42 lines
1 KiB
Rust

use std::fmt;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Complex {
real: i32,
imag: i32,
}
#[derive(Debug)]
struct InvalidComplex;
impl FromStr for Complex {
type Err = InvalidComplex;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = input.split('+').collect();
let real = parts[0].parse::<i32>().unwrap();
let imag = parts[1].trim_end_matches('i').parse::<i32>().unwrap();
Ok(Complex { real, imag })
}
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}+{}i", self.real, self.imag)
}
}
impl Solution {
pub fn complex_number_multiply(num1: String, num2: String) -> String {
let left: Complex = num1.parse().unwrap();
let right: Complex = num2.parse().unwrap();
(Complex {
real: left.real * right.real - left.imag * right.imag,
imag: left.real * right.imag + left.imag * right.real,
})
.to_string()
}
}