您的位置:首页 > 编程语言 > Java开发

43. Multiply Strings | Java最短代码实现

2016-03-19 19:22 447 查看
原题链接:43. Multiply Strings
【思路】

本题借用模拟大数精确乘法考查字符串的位操作。本解答先将结果缓存到 int 数组中,应用 int 数组的好处就是每一个int的值可以大于10:

public String multiply(String num1, String num2) {
int len1 = num1.length(), len2 = num2.length(), len = len1 + len2, count = 0;
int[] arr = new int[len];
for (int i = len1 - 1; i >= 0; i--) {
int bit1 = num1.charAt(i) - '0';
for (int j = len2 - 1, k = j + i + 1; j >= 0; j--, k--) {
int temp = bit1 * (num2.charAt(j) - '0') + arr[k];
arr[k] = temp % 10;
arr[k - 1] += temp / 10;
}
}
String s = "";
for (int i = 0; i < arr.length; i++)
s += arr[i];
while(count < len && s.charAt(count++) == '0');
return s.substring(count - 1);
}
311 / 311 test
cases passed. Runtime: 13
ms Your runtime beats 29.13% of javasubmissions.

【补充】

当然看到网上一种比较简洁而逗比的做法,我当时就笑了:

public String multiply(String num1, String num2) {
return new BigInteger(num1).multiply(new BigInteger(num2)) + "";
}
当然这种方法是通不过的,旨在逗大家一乐。

欢迎优化!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: