Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
2015.3 update
一个很简洁的做法:https://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/comment-page-1/#comment-122
public String multiply(String num1, String num2) {
num1 = new StringBuilder(num1).reverse().toString();
num2 = new StringBuilder(num2).reverse().toString();
int[] d = new int[num1.length() + num2.length()];
for (int i = 0; i < num2.length(); i++) {
int b = num2.charAt(i)-'0';
for (int j = 0; j < num1.length(); j++) {
int a = num1.charAt(j)-'0';
d[i+j] += a*b;
}
}
int carry = 0;
StringBuilder str = new StringBuilder();
for (int i = 0; i < d.length; i++) {
int tmp = d[i]+carry;
d[i] = tmp%10;
carry = tmp/10;
str.insert(0, d[i]);
}
if (carry > 0) {
str.insert(0, carry);
}
while (str.length() > 0 && str.charAt(0) == '0') {
str.deleteCharAt(0);
}
return str.toString().length() == 0 ? "0" : str.toString();
}
public String multiply(String num1, String num2) {
int n1 = num1.length();
int n2 = num2.length();
int[] a = new int[n1];
int[] b = new int[n2];
for (int i = n1 - 1; i >= 0; i--) {
a[i] = (int) (num1.charAt(n1 - i - 1) - '0');
}
for (int i = n2 - 1; i >= 0; i--) {
b[i] = (int) (num2.charAt(n2 - i - 1) - '0');
}
int carry = 0;
// store in reverse order
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < n2; i++) { // outer, b numbers
carry = 0;
int mul = b[i];
for (int j = 0; j < n1; j++) {
int tmp = mul * a[j] + carry;
if ((result.size() - 1) >= (i + j)) {
carry = (result.get(i + j) + tmp) / 10;
result.set(i + j, (result.get(i + j) + tmp) % 10);
} else {
result.add(tmp % 10);
carry = tmp / 10;
}
}
if (carry > 0) {
result.add(carry);
}
}
String ret = "";
boolean isFirst = true;
for (int i = result.size() - 1; i >= 0; i--) {
if (isFirst && result.get(i).equals(0)) {
continue;
}
ret = ret + (char) (result.get(i) + '0');
isFirst = false;
}
return ret.isEmpty() ? "0" : ret;
}