iven two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Java:
1. http://blog.csdn.net/fightforyourdream/article/details/17370495
这个好理解点
public class Solution {
public String multiply(String num1, String num2) {
// reverse
String n1= new StringBuilder(num1).reverse().toString();
String n2= new StringBuilder(num2).reverse().toString();
int[] d= new int[n1.length()+n2.length()];//build array save product
for(int i=0;i<n1.length();i++)
{
for(int j=0;j<n2.length();j++)
{
d[i+j]+=(n1.charAt(i)-'0')*(n2.charAt(j)-'0');//accumulate at correct position
}
}
StringBuilder res = new StringBuilder();
for(int i=0;i<d.length;i++)
{
int digit=d[i]%10;//current position
int carry=d[i]/10;//carry position
if(i+1<d.length)
{
d[i+1]+=carry;
}
res.insert(0,digit);
}
//remove first 0
while(res.charAt(0)=='0'&&res.length()>1)
{
res.deleteCharAt(0);
}
return res.toString();
}
}
2. Code大神这个for循环里面不是太好理解
public class Solution {
public String multiply(String num1, String num2) {
if(num1==null||num2==null||num1.length()==0||num2.length()==0) return null;
if(num1.charAt(0)=='0') return "0";
if(num2.charAt(0)=='0') return "0";
StringBuilder res=new StringBuilder();
int num=0;
for(int i=num1.length()+num2.length();i>0;i--)
{
for(int j=Math.min(i-1,num1.length());j>0;j--)
{
if(i-j<=num2.length())
{
num+=(int)(num1.charAt(j-1)-'0')*(int)(num2.charAt(i-1-j)-'0');
}
}
if(i!=1||num>0) res.append(num%10);
num=num/10;
}
return res.reverse().toString();
}
}
3. 水印人生的数组法:http://gongxuns.blogspot.com/2013/01/leetcode-multiply-strings.html
public class Solution {
public String multiply(String num1, String num2) {
if(num1==null||num2==null||num1.length()==0||num2.length()==0) return "";
if(num1.charAt(0)=='0') return "0";
if(num1.charAt(0)=='0') return "0";
int[] num=new int[num1.length()+num2.length()];
for(int i=0;i<num1.length();i++){
int carry=0;
int a=num1.charAt(num1.length()-1-i)-'0';
for(int j=0;j<num2.length();j++){
int b=num2.charAt(num2.length()-1-j)-'0';
num[i+j]+=carry+a*b;
carry=num[i+j]/10;
num[i+j]%=10;
}
num[i+num2.length()]+=carry;
}
int i=num.length-1;
while(i>0&&num[i]==0) i--;
StringBuilder res= new StringBuilder("");
while(i>=0){
res.append((char)('0'+num[i]));
i--;
}
return res.toString();
}
}