rustgym/leetcode/
_43_multiply_strings.rs1struct Solution;
2
3impl Solution {
4 fn multiply(num1: String, num2: String) -> String {
5 let n1 = num1.len();
6 let n2 = num2.len();
7 let n3 = n1 + n2;
8 let mut v1: Vec<i32> = vec![0; n1];
9 let mut v2: Vec<i32> = vec![0; n2];
10 let mut v3: Vec<i32> = vec![0; n3];
11 let mut v4: Vec<i32> = vec![];
12 for (i, c) in num1.char_indices() {
13 v1[n1 - 1 - i] = (c as u8 - b'0') as i32;
14 }
15 for (i, c) in num2.char_indices() {
16 v2[n2 - 1 - i] = (c as u8 - b'0') as i32;
17 }
18 for i in 0..n1 {
19 for j in 0..n2 {
20 v3[i + j] += v1[i] * v2[j];
21 }
22 }
23 let mut carry = 0;
24 for i in 0..n3 {
25 v4.push((v3[i] + carry) % 10);
26 carry = (v3[i] + carry) / 10;
27 }
28 if carry != 0 {
29 v4.push(carry);
30 }
31 while let Some(0) = v4.last() {
32 v4.pop();
33 }
34 v4.reverse();
35 if v4.is_empty() {
36 "0".to_string()
37 } else {
38 v4.into_iter().map(|x| (x as u8 + b'0') as char).collect()
39 }
40 }
41}
42
43#[test]
44fn test() {
45 let num1 = "2".to_string();
46 let num2 = "3".to_string();
47 let res = "6".to_string();
48 assert_eq!(Solution::multiply(num1, num2), res);
49 let num1 = "123".to_string();
50 let num2 = "456".to_string();
51 let res = "56088".to_string();
52 assert_eq!(Solution::multiply(num1, num2), res);
53}