Skip to main content
Back to problems
#43
Medium Algorithms

Multiply strings

Math String Simulation
43.6% acceptance
Jan 12, 2026
7706
3671
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn multiply(num1: String, num2: String) -> String {
    // Handle edge cases
    if num1 == "0" || num2 == "0" {
      return "0".to_string();
    }
    
    let num1_bytes = num1.as_bytes();
    let num2_bytes = num2.as_bytes();
    let m = num1_bytes.len();
    let n = num2_bytes.len();
    
    // The result will have at most m + n digits
    let mut result = vec![0; m + n];
    
    // Multiply each digit of num1 with each digit of num2
    for i in (0..m).rev() {
      for j in (0..n).rev() {
        let digit1 = (num1_bytes[i] - b'0') as i32;
        let digit2 = (num2_bytes[j] - b'0') as i32;
        let mul = digit1 * digit2;
        
        // Position in result array
        let p1 = i + j;
        let p2 = i + j + 1;
        
        // Add to existing value and handle carry
        let sum = mul + result[p2];
        result[p2] = sum % 10;
        result[p1] += sum / 10;
      }
    }
    
    // Convert result to string, skipping leading zeros
    let mut res_str = String::new();
    let mut started = false;
    for &digit in &result {
      if digit != 0 || started {
        res_str.push((digit as u8 + b'0') as char);
        started = true;
      }
    }
    
    res_str
  }
}