Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
num1
and num2
is less than 110.num1
and num2
contain only digits 0-9.num1
and num2
do not contain any leading zero, except the number 0 itself.result
to store intermediate results, with size num1.size() + num2.size()
because the maximum length of the product can be this size.num1
from the end to the beginning and for each digit do the same with num2
.result
array.result
array to string, skipping leading zeros.Here is the C++ implementation:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::string multiply(std::string num1, std::string num2) {
if (num1 == "0" || num2 == "0") return "0";
int m = num1.size();
int n = num2.size();
std::vector<int> result(m + n, 0);
// Reverse both numbers to facilitate multiplication from least significant digit
std::reverse(num1.begin(), num1.end());
std::reverse(num2.begin(), num2.end());
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int mul = (num1[i] - '0') * (num2[j] - '0');
result[i + j] += mul;
// Carry handling
result[i + j + 1] += result[i + j] / 10;
result[i + j] %= 10;
}
}
// Find the first non-zero digit from the end
int i = m + n - 1;
while (i >= 0 && result[i] == 0) --i;
// Construct the final result string
std::string finalResult;
while (i >= 0) {
finalResult += std::to_string(result[i]);
--i;
}
return finalResult;
}
// Main function for testing
int main() {
std::string num1 = "123";
std::string num2 = "456";
std::cout << multiply(num1, num2) << std::endl; // Output should be "56088"
return 0;
}
num1
and num2
respectively. Each digit of num1
is multiplied with each digit of num2
.result
array used for storing intermediate digits.This solution efficiently multiplies two arbitrary-length numbers represented as strings without converting them directly to integers, adhering to the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?