题目:
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
题解:
我们小时候都学过多位数的乘法过程,都是每位相乘然后错位相加,那么这里就是用到这种方法,把错位相加后的结果保存到一个一维数组中,然后分别每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可,
为了避免溢出,显然应该考虑对应位相乘,求结果的每一位的值最后串在一起。
比如,217*561,个位=7*1,十位=1*1+7*6,百位 = 7*5+1*6+2*1,千位=2*6+1*5,万位=2*5。分别存进数组里面,在考虑低位向高位的进位。转换为字符串之后考虑首位为0的情况。
//43.字符串数字相乘
public String multiply(String num1,String num2){
//字符串反转
num1=new StringBuilder(num1).reverse().toString();
num2=new StringBuilder(num2).reverse().toString();
//两数相乘 最大位数为两者位数之和
int[] product=new int[num1.length()+num2.length()];
for(int i=0;i<num1.length();i++){
for(int j=0;j<num2.length();j++)
//先获取对应位相乘 不考虑进位
product[i+j]+=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');
}
//对进位进行处理
for(int i=0;i<product.length;i++){
if(product[i]>9){
product[i+1]+=product[i]/10;
product[i]%=10;
}
}
StringBuilder result=new StringBuilder();
for(int i=product.length-1;i>=0;i--)
result.append(product[i]);
//去除首部的0
while(result.charAt(0)=='0'&&result.length()>1)
result.deleteCharAt(0);
return result.toString();
}