Note: The numbers can be arbitrarily large and are non-negative.
Idea: An m digits number times a n digits number will produce a number with no more than m+n digits. So we initial an array "result" with m+n space to cache the result. Start from the end of the two ends of the string, multiple digit by digit. For example the i'th digit of num1 and the j'th digit of num2 (index from left to right), their product will be in the array's result[i+j+1] position. So just update in place in the "result" array.
When all the multiplication is done, skip the leading 0's (except the last digit) in the result array to produce the output string. The reason why we keep the last digit is because when "0"*any number, the last digit of the result is "0" that should be output.
Time: O(n^2) Space: O(n)
Code:
public class Solution {
public String multiply(String num1, String num2) {
if(num1==null||num2==null)
return null;
int[] result=new int[num1.length()+num2.length()];
for(int i=num1.length()-1;i>=0;i--)
{
int v1=(int)(num1.charAt(i)-'0');
int carry=0;
int j;
for(j=num2.length()-1;j>=0;j--)
{
int v2=(int)(num2.charAt(j)-'0');
int product=v1*v2+result[i+j+1]+carry;
result[i+j+1]=product%10;
carry=product/10;
}
result[i+j+1]=carry;
}
StringBuilder builder=new StringBuilder();
int i=0;
for(i=0;i<result.length-1;i++)
if(result[i]!=0)
break;
while(i<result.length)
{
builder.append(result[i]);
i++;
}
return builder.toString();
}
}
No comments:
Post a Comment