Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c1c681f

Browse files
author
Zhang Xiaodong
committed
solve 43
1 parent 00e0cc5 commit c1c681f

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@ mod s0039_combination_sum;
3838
mod s0040_combination_sum_ii;
3939
mod s0041_first_missing_positive;
4040
mod s0042_trapping_rain_water;
41+
mod s0043_multiply_strings;
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/**
2+
* [43] 字符串相乘
3+
*
4+
* 给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
5+
* 注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
6+
*
7+
* 示例 1:
8+
*
9+
* 输入: num1 = "2", num2 = "3"
10+
* 输出: "6"
11+
* 示例 2:
12+
*
13+
* 输入: num1 = "123", num2 = "456"
14+
* 输出: "56088"
15+
*
16+
* 提示:
17+
*
18+
* 1 <= num1.length, num2.length <= 200
19+
* num1 和 num2 只能由数字组成。
20+
* num1 和 num2 都不包含任何前导零,除了数字0本身。
21+
*
22+
*/
23+
pub struct Solution {}
24+
25+
// problem: https://leetcode.cn/problems/multiply-strings/
26+
// discuss: https://leetcode.cn/problems/multiply-strings/discuss/?currentPage=1&orderBy=most_votes&query=
27+
28+
// submission codes start here
29+
30+
use std::char;
31+
32+
impl Solution {
33+
34+
fn assign_digit(res: &mut Vec<u32>, k: usize, v: u32) {
35+
if k >= res.len() {
36+
res.push(v);
37+
} else {
38+
res[k] += v;
39+
}
40+
let mut k = k;
41+
while res[k] > 10 {
42+
if k == res.len() - 1 {
43+
res.push(res[k]/10);
44+
res[k] %= 10;
45+
break;
46+
} else {
47+
res[k+1] += res[k] / 10;
48+
res[k] %= 10;
49+
}
50+
k += 1;
51+
}
52+
}
53+
54+
pub fn multiply(num1: String, num2: String) -> String {
55+
if num1 == "0" || num2 == "0" {
56+
return "0".to_string();
57+
}
58+
let mut res = vec![];
59+
60+
let mut digits1 = vec![];
61+
for c in num1.chars().rev() {
62+
digits1.push(c.to_digit(10).unwrap());
63+
}
64+
65+
for (i, c) in num2.chars().rev().enumerate() {
66+
let d2 = c.to_digit(10).unwrap();
67+
for (j, d1) in digits1.iter().enumerate() {
68+
Self::assign_digit(&mut res, i + j, d1 * d2);
69+
}
70+
}
71+
let mut s = "".to_string();
72+
for d in res.iter().rev() {
73+
s.push(char::from_digit(*d, 10).unwrap());
74+
}
75+
s
76+
}
77+
}
78+
79+
// submission codes end
80+
81+
#[cfg(test)]
82+
mod tests {
83+
use super::*;
84+
85+
#[test]
86+
fn test_43() {
87+
assert_eq!(Solution::multiply("123".to_string(), "23".to_string()), "2829".to_string());
88+
assert_eq!(Solution::multiply("982634".to_string(), "2343".to_string()), "2302311462".to_string());
89+
}
90+
}

0 commit comments

Comments
 (0)