Algo-Sim › Math & Geometry
Multiply Strings
Medium · Math & Geometry · step through it in Java, Python and C++ on your own input
Grade-school multiplication on digit arrays: num1[i] × num2[j] adds into positions i + j and i + j + 1. O(m·n), no big integers.
Problem
Given two non-negative integers num1 and num2 written as strings, return their product, also as a string. You must not use a big-integer library or convert the inputs to integers directly.
Constraints
- 1 ≤ num1.length, num2.length ≤ 200
- Digits only
- No leading zeros except the number 0 itself
Edge cases to test
- One operand
"0" - Single digits
- Results with a leading zero to strip
Follow-up questions
- Can you beat O(m·n)?
- Karatsuba splits each number in half and uses three multiplications instead of four: O(n^1.585). FFT gets O(n log n).
- Why is the result at most m + n digits?
- Both numbers are below 10^m and 10^n, so the product is below 10^(m + n).
Solution
Java
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n];
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int sum = mul + pos[i + j + 1];
pos[i + j] += sum / 10;
pos[i + j + 1] = sum % 10;
}
}
StringBuilder sb = new StringBuilder();
for (int d : pos) if (sb.length() > 0 || d != 0) sb.append(d);
return sb.length() == 0 ? "0" : sb.toString();
}Python
def multiply(num1, num2):
m, n = len(num1), len(num2)
pos = [0] * (m + n)
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
mul = int(num1[i]) * int(num2[j])
total = mul + pos[i + j + 1]
pos[i + j] += total // 10
pos[i + j + 1] = total % 10
digits = "".join(map(str, pos)).lstrip("0")
return digits or "0"C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string multiply(string &num1, string &num2) {
int m = int(num1.size()), n = int(num2.size());
vector<int> pos = vector<int>(m + n);
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int mul = (num1[i] - '0') * (num2[j] - '0');
int sum = mul + pos[i + j + 1];
pos[i + j] += sum / 10;
pos[i + j + 1] = sum % 10;
}
}
string sb = string();
for (int d : pos)
if (int(sb.size()) > 0 || d != 0)
sb.push_back(char('0' + d));
return int(sb.size()) == 0 ? "0" : sb;
}
};
More Math & Geometry problems
- Plus One (Easy)
- Happy Number (Easy)
- GCD and LCM (Euclid) (Easy)
- Count Primes (Sieve of Eratosthenes) (Medium)
- Pow(x, n) (Medium)
- Count Good Numbers (mod 1e9+7) (Medium)
- Reverse Integer (Medium)
- String to Integer (atoi) (Medium)
- Detect Squares (Medium)
- Random Pick with Weight (Medium)
- Shuffle an Array (Medium)
- Linked List Random Node (Medium)
- Pascal's Triangle (Easy)
- nCr mod p (Medium)
- Max Points on a Line (Hard)