【leetcode刷题笔记】Multiply Strings

时间:2023-03-10 02:26:43
【leetcode刷题笔记】Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.


题解:就是让实现一个大整数乘法。

假设两个数num1和num2的长度分别是len1和len2,那么最后得到的答案,在最高位有进位的时候,就是len1+len2位,否则是len1+len2-1位。我们用数组numbers[len1+len2]存放最后的结果。

很关键的一点就是在做每位之间的乘法的时候不要处理进位,在做加法的时候同一处理进位。

举个例子,12*16,我们从最低位开始相乘:

【leetcode刷题笔记】Multiply Strings

num1[i]和num2[j]对应的数相乘的积在numbers数组中存放的位置是numbers[i+j+1]。

两个数相乘最高位的进位存放在numbers[0]中,在把字符数组转换成数字的时候要单独处理;另外下面的代码中29~32行是为了避免结果出现类似“0000”这种情况,这时应该返回结果0。

代码如下:

 public class Solution {
public String multiply(String num1, String num2) {
if(num1 == null || num2 == null)
return null;
int len1 = num1.length();
int len2 = num2.length();
int len3 = len1 + len2;
int[] numbers = new int[len3]; int i,j; for(i = len1-1;i >= 0;i--){
for(j=len2-1;j >= 0;j--){
numbers[i+j+1] += (num1.charAt(i)-'0') * (num2.charAt(j)-'0');
}
} int carries = 0;
for(i = len3-1;i >=0;i--){
numbers[i] += carries;
carries = numbers[i]/10;
numbers[i] %= 10;
} StringBuffer sBuffer = new StringBuffer();
sBuffer.append(numbers[0]==0?"":numbers[0]);
i = 1;
if(sBuffer.length() == 0){
while(i < len3 && numbers[i]== 0)
i++;
}
for(;i <len3;i++)
sBuffer.append(numbers[i]);
if(sBuffer.length() == 0)
sBuffer.append(0);
return sBuffer.toString();
}
}