Multiply Strings

medium string math simulation

Problem

Given two non-negative integers num1 and num2 represented as strings, return their product as a string. Do not convert directly to BigInteger or call any built-in big-number library.

Inputnum1 = "123", num2 = "456"
Output"56088"
Digit (i, j) contributes to positions i+j and i+j+1 of the result.

def multiply(num1, num2):
    if num1 == "0" or num2 == "0": return "0"
    m, n = len(num1), len(num2)
    res = [0] * (m + n)
    for i in range(m - 1, -1, -1):
        for j in range(n - 1, -1, -1):
            mul = (ord(num1[i]) - 48) * (ord(num2[j]) - 48)
            p1, p2 = i + j, i + j + 1
            total = mul + res[p2]
            res[p2] = total % 10
            res[p1] += total // 10
    return "".join(map(str, res)).lstrip("0") or "0"
function multiply(num1, num2) {
  if (num1 === "0" || num2 === "0") return "0";
  const m = num1.length, n = num2.length;
  const res = new Array(m + n).fill(0);
  for (let i = m - 1; i >= 0; i--) {
    for (let j = n - 1; j >= 0; j--) {
      const mul = (num1.charCodeAt(i) - 48) * (num2.charCodeAt(j) - 48);
      const p1 = i + j, p2 = i + j + 1;
      const total = mul + res[p2];
      res[p2] = total % 10;
      res[p1] += Math.floor(total / 10);
    }
  }
  return res.join("").replace(/^0+/, "") || "0";
}
class Solution {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) return "0";
        int m = num1.length(), n = num2.length();
        int[] res = 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 p1 = i + j, p2 = i + j + 1;
                int total = mul + res[p2];
                res[p2] = total % 10;
                res[p1] += total / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int d : res) if (!(sb.length() == 0 && d == 0)) sb.append(d);
        return sb.length() == 0 ? "0" : sb.toString();
    }
}
string multiply(string num1, string num2) {
    if (num1 == "0" || num2 == "0") return "0";
    int m = num1.size(), n = num2.size();
    vector<int> res(m + n, 0);
    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 p1 = i + j, p2 = i + j + 1;
            int total = mul + res[p2];
            res[p2] = total % 10;
            res[p1] += total / 10;
        }
    }
    string out;
    for (int d : res) if (!(out.empty() && d == 0)) out += (char)('0' + d);
    return out.empty() ? "0" : out;
}
Time: O(m · n) Space: O(m + n)