题目:
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:
- The length of both num1 and num2 is < 110.
- Both num1 and num2 contain only digits 0-9.
- Both num1 and num2 do 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.
解答:
这道题的整体思路与我们通过竖式计算的方法基本相同,即从一个数的最低位开始,依次与另一个数相乘。
通过竖式相乘的过程和最终结果我们可以发现,若第一个数的第 i 位与第二个数的第 j 位相乘,得到的数对应最终计算结果的第 i+j 位。
为了简化计算过程,我们可以先省略进位,在得到相乘结果的数组后,再从最低位开始依次进行进位处理。
1 2 3
× 4 5 6
__________________________
6 12 18
+ 5 10 15
+ 4 8 12
——————————————————————————
4 13 28 27 18 (数组 res 存储计算结果)
↓(进位处理)
5 6 0 8 8 (最终结果)
综上,具体思路如下:
- 创建 res 数组用于存储相乘结果。一个 m 位的数与一个 n 位的数相乘,则结果最高为 m+n-1 位。(第一次提交时,创建数组长度为 m+n,则会导致错误,如 2*3,最低位会被初始化为0,计算结果会错为 60)
- 通过 ASCII 码相减
num1.charAt(i) - 48
将数字字符转换为 int 类型,并逐位相乘,相加至对应位置 - 从低位开始对 res 中结果进行逐位进位,i 位置对应的最终计算结果为 res[i]%10,res/10 为进位结果并加至高一位
- 通过 StringBuffer.append() 方法将数组中结果转为字符串类型并输出
class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0")) {
return "0";
}
int len1 = num1.length();
int len2 = num2.length();
int[] res = new int[len1+len2-1];
//逐位相乘
for(int i=0; i<len1; i++) {
for(int j=0; j<len2; j++) {
int one = num1.charAt(i) - 48;
int two = num2.charAt(j) - 48;
res[i+j] += one * two;
}
}
//进位处理
for(int i=res.length-1; i>0; i--) {
res[i-1] += res[i]/10;
res[i] %= 10;
}
StringBuffer str = new StringBuffer();
for(int i=0; i<res.length; i++) {
str.append(res[i]);
}
return str.toString();
}
}