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.
public class Solution {
public String multiply(String num1, String num2) {
String st1 = new StringBuilder(num1).reverse().toString();
String st2 = new StringBuilder(num2).reverse().toString();
int[] res = new int[st1.length()+st2.length()];
for (int i = 0; i < st1.length(); i++) {
for (int j = 0; j < st2.length(); j++) {
res[i+j] += (st1.charAt(i)-'0')*(st2.charAt(j)-'0');
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < res.length; i++) {
int digit = res[i]%10;
int carry = res[i]/10;
if (i+1 < res.length) {
res[i+1] += carry;
}
sb.insert(0, digit);
}
while (sb.charAt(0)=='0' && sb.length()>1) {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
本文介绍了一种用于计算两个任意大数字符串乘积的方法,通过构建字符串反转、逐位相乘、进位处理及结果拼接的过程,实现字符串数字的乘法运算。
1003

被折叠的 条评论
为什么被折叠?



