问题原始链接 https://leetcode.com/problems/multiply-strings
给定两个以字符串表示的数,以字符串形式返回这两个数的乘积。
注意:
数非负并且可以任意大。
不允许把输入字符串转换成整数。
不允许使用内部库比如BigInteger。
public class Solution {
public static String multiply(String num1, String num2) {
StringBuilder sb = new StringBuilder();
for (int i = num2.length() - 1; i >= 0; i--) {
int carry = 0;
int x1 = Character.getNumericValue(num2.charAt(i));
if (x1 == 0) {
continue;
}
for (int j = num1.length() - 1; j >= 0; j--) {
int x2 = Character.getNumericValue(num1.charAt(j));
if (x2 == 0 && carry == 0) {
continue;
}
int k = (num2.length() - 1 - i) + (num1.length() - 1 - j);
int x3 = k < sb.length() ? Character.getNumericValue(sb.charAt(k)) : 0;
int v = x1 * x2 + x3 + carry;
int d = v % 10;
carry = v / 10;
while (sb.length() < k) {
sb.append('0');
}
if (k < sb.length()) {
sb.setCharAt(k, (char) (d + '0'));
} else {
sb.append((char) (d + '0'));
}
}
if (carry > 0) {
sb.append(carry);
}
}
return sb.length() == 0 ? "0" : sb.reverse().toString();
}
}