1. Iterative Row Multiplication and Addition
Intuition
For each digit in num2 from right to left, multiply num1 by that single digit to get an intermediate string, append appropriate number of trailing zeros, and add it to a running total string using a helper addStrings() function.
When to apply: When building directly on top of the Add Strings problem.
Algorithm
- If
num1 == "0"ornum2 == "0", return"0". - Initialize
total = "0". - Loop
jfromnum2.length - 1down to 0: - Multiply
num1bynum2[j]with carry ->row. - Append
(num2.length - 1 - j)zeros torow. -
total = addStrings(total, row). - Return
total.
Iterative Row Multiplication and Addition
2 of 2 questions left todayObservation: In traditional paper multiplication, multiply the top number num1 = '12' by each digit of num2
Observation: In traditional paper multiplication, multiply the top number num1 = '12' by each digit of num2.
Decision: Multiply by units digit 4: 12 × 4 = 48. Store first row as '48'.
Invariant: Each row represents num1 × d_2 × 10k.
#include <iostream>#include <string>#include <vector>#include <algorithm> class Solution { std::string addStrings(std::string num1, std::string num2) { std::string res = ""; int i = num1.size() - 1, j = num2.size() - 1, carry = 0; while (i >= 0 || j >= 0 || carry) { int sum = carry; if (i >= 0) sum += num1[i--] - '0'; if (j >= 0) sum += num2[j--] - '0'; carry = sum / 10; res.push_back((sum % 10) + '0'); } std::reverse(res.begin(), res.end()); return res; }public: std::string multiply(std::string num1, std::string num2) { if (num1 == "0" || num2 == "0") return "0"; int n = num1.size(), m = num2.size(); std::string total = "0"; for (int j = m - 1; j >= 0; --j) { std::string row = ""; int carry = 0, d2 = num2[j] - '0'; for (int i = n - 1; i >= 0; --i) { int prod = (num1[i] - '0') * d2 + carry; carry = prod / 10; row.push_back((prod % 10) + '0'); } if (carry) row.push_back(carry + '0'); std::reverse(row.begin(), row.end()); row.append(m - 1 - j, '0'); total = addStrings(total, row); } return total; }}; int main() { Solution sol; std::cout << sol.multiply("123", "456") << std::endl; // 56088 return 0;}Time & Space Complexity
- Time complexity:
O(N * M + M^2)— Performs M multiplications of size N and M string additions of increasing lengths. - Space complexity:
O(N + M)
Why Brute Force Doesn't Scale:
Single pre-allocated array of size N + M eliminates intermediate string allocations.
Direct in-place carry propagation avoids separate addition routines.