Created
April 11, 2023 14:31
-
-
Save zRains/a594e69faf3f24bf8fad93e9a41a5aea to your computer and use it in GitHub Desktop.
Add two big nums.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![allow(unused)] | |
| pub fn add_big_num(num_1: &str, num_2: &str) -> String { | |
| let to_u8_arr = |num: &str| { | |
| num.split("") | |
| .filter(|&n| !n.is_empty()) | |
| .map(|n| n.parse::<u8>().unwrap()) | |
| .collect::<Vec<_>>() | |
| }; | |
| let mut num_1_arr = to_u8_arr(num_1); | |
| let mut num_2_arr = to_u8_arr(num_2); | |
| match num_1.len().cmp(&num_2.len()) { | |
| std::cmp::Ordering::Greater => { | |
| num_2_arr.splice(0..0, vec![0; num_1.len() - num_2.len()]); | |
| } | |
| _ => { | |
| num_1_arr.splice(0..0, vec![0; num_2.len() - num_1.len()]); | |
| } | |
| } | |
| let mut padding = 0u8; | |
| for idx in (0..num_1_arr.len()).rev() { | |
| let current = num_2_arr[idx] + num_1_arr[idx] + padding; | |
| num_1_arr[idx] = current % 10; | |
| padding = current / 10; | |
| } | |
| if padding != 0 { | |
| num_1_arr.insert(0, padding); | |
| } | |
| num_1_arr | |
| .iter() | |
| .map(|x| x.to_string()) | |
| .collect::<Vec<_>>() | |
| .join("") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment