Skip to content

Instantly share code, notes, and snippets.

@guolinaileen
Created March 9, 2013 04:19
Show Gist options
  • Save guolinaileen/5122508 to your computer and use it in GitHub Desktop.
Save guolinaileen/5122508 to your computer and use it in GitHub Desktop.
public class Solution {
public String multiply(String num1, String num2) {
// Start typing your Java solution below
// DO NOT write main() function
if(num1.compareTo("0")==0 || num2.compareTo("0")==0 ) return "0";
int length1=num1.length(); int length2=num2.length();
int [] array=new int [length1+length2];
int carry=0;
for(int i=length1-1; i>=0; i--)
{
for(int j=length2-1; j>=0; j--)
{
int temp=array[length1+length2-2-i-j];
temp+=(num1.charAt(i)-'0')*(num2.charAt(j)-'0')+carry;
if(temp>=10)
{
carry=temp/10; temp%=10;
}else carry=0;
array[length1+length2-2-i-j]=temp;
}
if(carry!=0)
{
array[length1+length2-i-1]=carry; carry=0;
}
}
StringBuffer sb=new StringBuffer();
if(array[length1+length2-1]!=0) sb.append(array[length1+length2-1]);
for(int i=length1+length2-2; i>=0; i--)
{
sb.append(array[i]);
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment