43. Multiply Strings Medium
1/**
2 * [43] Multiply Strings
3 *
4 * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
5 * Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
6 *
7 * Example 1:
8 * Input: num1 = "2", num2 = "3"
9 * Output: "6"
10 * Example 2:
11 * Input: num1 = "123", num2 = "456"
12 * Output: "56088"
13 *
14 * Constraints:
15 *
16 * 1 <= num1.length, num2.length <= 200
17 * num1 and num2 consist of digits only.
18 * Both num1 and num2 do not contain any leading zero, except the number 0 itself.
19 *
20 */
21pub struct Solution {}
22
23// problem: https://leetcode.com/problems/multiply-strings/
24// discuss: https://leetcode.com/problems/multiply-strings/discuss/?currentPage=1&orderBy=most_votes&query=
25
26// submission codes start here
27
28impl Solution {
29 pub fn multiply(num1: String, num2: String) -> String {
30 let mut r: Vec<i32> = vec![0; num1.len() + num2.len()];
31 for (i, v1) in num1.chars().rev().enumerate() {
32 for (j, v2) in num2.chars().rev().enumerate() {
33 let got = (v1 as i32 - '0' as i32) * (v2 as i32 - '0' as i32);
34 let n = got + r[i + j];
35 r[i + j] = n % 10;
36 r[i + j + 1] += n / 10;
37 }
38 }
39 let mut result = String::new();
40 for i in r.into_iter().rev() {
41 if result.is_empty() && i == 0 {
42 continue;
43 } else {
44 result.push(char::from_digit(i as u32, 10).unwrap());
45 }
46 }
47 if result.is_empty() {
48 String::from("0")
49 } else {
50 result
51 }
52 }
53}
54
55// submission codes end
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn test_43() {
63 assert_eq!(
64 "56088".to_owned(),
65 Solution::multiply("123".to_string(), "456".to_string())
66 );
67 }
68}
69
Back
© 2025 bowen.ge All Rights Reserved.