【题目】
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.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
计算大数乘法。其中大数是以字符串的形式表示,任意大,非负,返回结果以字符串形式
【分析】
假设两个字符串的长度分别为了a和b,可以得出最后结果长度为a+b(最后有进位)或者a+b-1(最后没有有进位)。由此程序中得先用长度为a+b的数组记录结果,最后再转成字符串。在计算时,先把各个位的相乘结果对应累加起来,例如第1个整数的第i位(低位到高位)和第2个整数的第j位(低位到高位)相乘的结果应该存放在数组的i+j位。然后再统一处理进位。在将数组转换成字符串前,需要跳过前面的零,如果结果只有0,则只返回0。
注意:乘法计算中可以发现,结果中第i
位,应该由第一个字符串中的第1
位乘以第二个字符串中的第i
位,第一个字符串中的第2
位乘以第二个字符串中的第i-1
位,.......第一个字符串中的第i
位乘以第二个字符串中的第1
位,最后累加求得,最后我们取个位上的数值,然后剩下的作为进位放到下一轮循环中
//分别对两个开始字符串进行转置,便于后面的下标遍历
【实现】
public String multiply(String num1, String num2) {
String a = new StringBuilder(num1).reverse().toString();
String b = new StringBuilder(num2).reverse().toString();
int[] tem = new int[num1.length()+num2.length()];
for(int i=0; i<a.length(); i++){
for(int j=0; j<b.length(); j++){
tem[i+j] += (a.charAt(i)-'0') * (b.charAt(j)-'0');
}
}
StringBuilder res = new StringBuilder();
//计算每一位
for(int i=0; i<tem.length; i++){
int mod = tem[i]%10;
int jinwei = tem[i]/10;
if(i+1<tem.length){
tem[i+1] += jinwei;
}
res.insert(0, mod);
}
//remove front 0's
while(res.charAt(0) == '0' && res.length()> 1){
res.deleteCharAt(0);
}
return res.toString();
}
时间复杂度两个字符串长度的乘积,空间复杂度是 两个字符串长度的和
public String multiply(String num1, String num2) {
BigInteger n1 = new BigInteger(num1);
BigInteger n2 = new BigInteger(num2);
return n1.multiply(n2).toString();
}
}