From 8a60920998efe8cdb8c1c98e8669e366affd695e Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Fri, 28 Oct 2022 17:10:36 -0700 Subject: [PATCH] bigint for strings works with my compiler, but not leetcode's --- multiply_strings/Cargo.toml | 8 +++++ multiply_strings/src/main.rs | 67 ++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 multiply_strings/Cargo.toml create mode 100644 multiply_strings/src/main.rs diff --git a/multiply_strings/Cargo.toml b/multiply_strings/Cargo.toml new file mode 100644 index 0000000..756474d --- /dev/null +++ b/multiply_strings/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "multiply_strings" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/multiply_strings/src/main.rs b/multiply_strings/src/main.rs new file mode 100644 index 0000000..57356ca --- /dev/null +++ b/multiply_strings/src/main.rs @@ -0,0 +1,67 @@ +pub fn multiply(num1: String, num2: String) -> String { + // + + let mut out: Vec = Vec::from_iter((0..(num1.len() + num2.len())).into_iter().map(|_| 0)); + + let l1 = num1.len(); + let l2 = num2.len(); + + // get the longest one as num1 + let (num1, num2) = if l1 < l2 { (num2, num1) } else { (num1, num2) }; + + for (i2, d2) in num2.chars().rev().enumerate() { + let mut mcarry = 0; + let mut tmp = Vec::from_iter((0..i2).into_iter().map(|_| 0)); + let d2 = d2.to_digit(10).unwrap(); + for d1 in num1.chars().rev() { + let d1 = d1.to_digit(10).unwrap(); + let p = (d1 * d2) + mcarry; + mcarry = p / 10; + let p = p % 10; + tmp.push(p); + } + if mcarry > 0 { + tmp.push(mcarry); + } + merge(&mut out, &tmp); + } + let out = if let Some(last) = out.last() { + if *last == 0 { + let len = out.len() - 1; + &out[0..len] + } else { + &out[0..] + } + } else { + &out[0..] + }; + + out.iter().rev().map(|d| d.to_string()).collect() +} + +fn merge(out: &mut [u32], rhs: &[u32]) { + // + let mut acarry = 0; + let len = rhs.len(); + (0..len).for_each(|i| { + let oi = out[i]; + let ri = rhs[i]; + let s = oi + ri + acarry; + acarry = s / 10; + let s = s % 10; + out[i] = s; + }); + if acarry > 0 { + out[len] = acarry; + } +} + +fn main() { + dbg!(multiply("2".to_string(), "4".to_string())); + dbg!(multiply("27".to_string(), "49".to_string())); + dbg!(multiply( + "20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + .to_string(), + "4000000000000000000000000000000000000000000000000000000000000000".to_string() + )); +}