0043. Multiply Strings (M)

Multiply Strings (M)

题目

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:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

题意

不使用内建库实现大数乘法。

思路

  1. m位数乘n位数得到的积最大位数为m+n,直接开一个m+n大的数组来存储积的每一位数;
  2. num1中i位置的数与num2中j位置的数相乘,所得积在新数组中的位置为i+j+1(位置i+j是留给进位的),每次计算积后累加在对应位置,可以先不考虑进位,之后再处理;
  3. 从右向左遍历新数组,处理进位;
  4. 将新数组转化为字符串。(注意第一个元素为0的情况)

代码实现

Java

class Solution {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }

        int[] array = new int[num1.length() + num2.length()];
        for (int i = 0; i < num1.length(); i++) {
            for (int j = 0; j < num2.length(); j++) {
                int x = num1.charAt(i) - '0';
                int y = num2.charAt(j) - '0';
                array[i + j + 1] += x * y;
            }
        }

        int carry = 0;
        for (int i = array.length - 1; i >= 0; i--) {
            int sum = array[i] + carry;
            array[i] = sum % 10;
            carry = sum / 10;
        }

        StringBuilder sb = new StringBuilder();
        // 第一个为0则不加入字符串中
        for (int i = array[0] == 0 ? 1 : 0; i < array.length; i++) {
            sb.append((char) (array[i] + '0'));
        }

        return sb.toString();
    }
}

JavaScript

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var multiply = function (num1, num2) {
  if (num1 === '0' || num2 === '0') {
    return '0'
  }

  let product = new Array(num1.length + num2.length).fill(0)
  for (let i = 0; i < num1.length; i++) {
    for (let j = 0; j < num2.length; j++) {
      product[i + j + 1] += num1[i] * num2[j]
    }
  }

  for (let i = product.length - 1; i >= 0; i--) {
    if (i > 0 && product[i] >= 10) {
      product[i - 1] += Math.trunc(product[i] / 10)
      product[i] %= 10
    }
  }

  if (product[0] === 0) {
    product = product.slice(1)
  }

  return product.join('')
}


参考

Black_Knight - LeetCode 43. Multiply Strings

原文地址:https://www.cnblogs.com/mapoos/p/13205889.html