Multiply Strings
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.
解题思路:
这道题既然不能将string直接转换为整数,又要做乘法,那就只能对两个数的每一位进行相乘,存在一个数组里面,最后对数组进行处理了。
比如我们的456*123,大概可以看成这样:
然后再从后往前对每个值进行更新,将个位数作为当前的值,十位以上的作为进位到数组的前一个量。这样就可以实现乘法运算了。最后把数组中前面的为0的量去掉就可。
public class Solution {
public String multiply(String num1, String num2) {
//两个string转为int数组
if(num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0)
return "";
int[] add1 = new int[num1.length()];
for(int i = 0;i<num1.length();i++)
add1[i] = Integer.parseInt(num1.substring(i, i+1));
int[] add2 = new int[num2.length()];
for(int i = 0;i<num2.length();i++)
add2[i] = Integer.parseInt(num2.substring(i, i+1));
int[] result = new int[num1.length()+num2.length()-1];
//进行每一位的相乘
for(int i = 0;i< add1.length;i++)
for(int j = 0;j< add2.length;j++)
result[i+j] += add1[i]*add2[j];
int numx = 0;
String rs = "";
//反向更新数组的值,并转为string
for(int i = result.length-1;i>=0;i--)
{
result[i] += numx;
numx = result[i]/10;
result[i] = result[i]%10;
rs = String.valueOf(result[i]) + rs;
}
//去掉前面为0的部分
if(numx > 0)
rs = String.valueOf(numx) + rs;
int index = 0;
while(index < rs.length() && rs.charAt(index++) == '0');
return rs.substring(index-1, rs.length());
}
}