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 static void main(String[] args) {
System.out.println(multiply("0", "0"));
}
public static String multiply(String num1, String num2) {
if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) return "";
int[] number1 = toIntegerArray(num1);
int[] number2 = toIntegerArray(num2);
int[] result = new int[num1.length() + num2.length()];
int startIndex = 0;
for (int i = num1.length() - 1; i >= 0; i--) {
int extra = 0;
for (int j = num2.length() - 1; j >= 0; j--) {
int value = number1[i] * number2[j] + result[(result.length - 1) - startIndex + j - (num2.length() - 1)] + extra;
extra = value / 10;
value = value % 10;
result[(result.length - 1) - startIndex + j - (num2.length() - 1)] = value;
}
result[(result.length - 1) - startIndex -1 - (num2.length() - 1)] = extra;
startIndex++;
}
String str = "";
boolean isBeginningZero = true;
for (int i = 0; i < result.length; i++) {
if (result[i] == 0 && isBeginningZero == true) {
} else {
isBeginningZero = false;
str += result[i];
}
}
return str == "" ? "0" : str;
}
public static int[] toIntegerArray(String num) {
if (num == null || num.length() == 0) return null;
int length = num.length();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = num.charAt(i) - '0';
}
return arr;
}
}
本文介绍了一种处理任意精度大数乘法的方法,通过将字符串形式的大整数转换为整型数组,再利用传统的乘法算法进行计算,并将结果转换回字符串形式返回。这种方法适用于超出常规整型变量表示范围的极大数值。
1014

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



