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.
首先,展示一个我看到的最吊,碉堡了的算法:
import java.math.BigInteger;
public class Solution {
public String multiply(String num1, String num2) {
BigInteger n1 = new BigInteger(num1);
BigInteger n2 = new BigInteger(num2);
return n1.multiply(n2).toString();
}
}
这个居然可以AC。厉害!利用Java的BigInteger就可以轻松完成这个任务。
其次说一下正经的算法,就是模拟手算乘法:(这个是我找到的我认为最漂亮的代码)
首先我们要注意,这种大数相乘、相加的题目,都要先Reverse才方便我们思考计算。Reverse的代码是
num1 = new StringBuilder(num1).reverse().toString();
num2 = new StringBuilder(num2).reverse().toString();
其次我们要知道,两数相乘最大结果的长度来设置结果数组:
int[] d = new int[num1.length() + num2.length()];
再者我们要注意char和int如何互相转换:
int a = num1.charAt(i) - '0';
主要算法是先讲每一位相乘结果存入数组,然后再进行加法模拟进位计算。在加法过程中利用了StringBuilder。
public class Solution {
public String multiply(String num1, String num2) {
num1 = new StringBuilder(num1).reverse().toString();
num2 = new StringBuilder(num2).reverse().toString();
// even 99 * 99 is < 10000, so maximaly 4 digits
int[] d = new int[num1.length() + num2.length()];
for (int i = 0; i < num1.length(); i++) {
int a = num1.charAt(i) - '0';
for (int j = 0; j < num2.length(); j++) {
int b = num2.charAt(j) - '0';
d[i + j] += a * b;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < d.length; i++) {
int digit = d[i] % 10;
int carry = d[i] / 10;
sb.insert(0, digit);
if (i < d.length - 1)
d[i + 1] += carry;
}
//trim starting zeros
while (sb.length() > 0 && sb.charAt(0) == '0') {
sb.deleteCharAt(0);
}
return sb.length() == 0 ? "0" : sb.toString();
}
}