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:
The length of both
num1andnum2is < 110.Both
num1andnum2contain only digits0-9.Both
num1andnum2do not contain any leading zero, except the number 0 itself.You must not use any built-in BigInteger library or convert the inputs to integer directly.
Analysis & Solution
九章的解法要点:
两个位数为
m和n的数字相乘,乘积不会超过m + n位。乘法操作从右往左计算时,每次完成相加就确定了当前 digit. 并且是在
res[i + j + 1]位上,需要跟当前值,进位值共同确定最终保留的digit。同一个 digit 多次修改,用
int[ ].
更优雅的方法 by yavinci:
基于了一个乘法特性:每个数字相乘时:
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?