Multiply Strings

String, Math

Medium

Given two non-negative integersnum1andnum2represented as strings, return the product ofnum1andnum2, 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 num1and num2is < 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.

Analysis & Solution

九章的解法要点:

  • 两个位数为 mn 的数字相乘,乘积不会超过 m + n 位。

  • 乘法操作从右往左计算时,每次完成相加就确定了当前 digit. 并且是在res[i + j + 1]位上,需要跟当前值,进位值共同确定最终保留的digit。

  • 同一个 digit 多次修改,用 int[ ].

更优雅的方法 by yavinci

https://leetcode.com/problems/multiply-strings/discuss/17605/Easiest-JAVA-Solution-with-Graph-Explanation

基于了一个乘法特性:每个数字相乘时:

Code:

Reference

https://mnmunknown.gitbooks.io/algorithm-notes/525_string_za_ti.html

https://leetcode.com/problems/multiply-strings/discuss/17608/AC-solution-in-Java-with-explanation

Last updated

Was this helpful?