Created
July 6, 2013 14:05
-
-
Save jimexist/5939985 to your computer and use it in GitHub Desktop.
leet code solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public String multiply(String num1, String num2) { | |
return toString(mult(toIntArray(num1), toIntArray(num2))); | |
} | |
private int[] toIntArray(String s) { | |
int[] result = new int[s.length()]; | |
for (int i=0; i<result.length; ++i) { | |
result[i] = Character.digit(s.charAt(s.length()-1-i), 10); | |
} | |
return result; | |
} | |
private String toString(int[] arr) { | |
StringBuilder sb = new StringBuilder(arr.length); | |
int i=arr.length-1; | |
while (arr[i] == 0 && i>0) --i; | |
for (; i>=0; --i) { | |
sb.append(arr[i]); | |
} | |
return sb.toString(); | |
} | |
private int[] mult(int[] a1, int[] a2) { | |
int[] result = new int[a1.length+a2.length]; | |
for (int i=0; i<a1.length; ++i) { | |
int m = a1[i]; | |
for (int j=i; j<a2.length+i;++j) { | |
result[j] += a2[j-i]*m; | |
} | |
} | |
for (int i=0; i<result.length-1; ++i) { | |
result[i+1]+=result[i] / 10; | |
result[i] = result[i] % 10; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment