用java实现一个输入任意值的大整数的乘法运算
时间: 2023-05-24 13:01:57 浏览: 108
好的,以下是一个Java代码实现大整数乘法运算的示例:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();
System.out.println(multiply(str1, str2));
}
private static String multiply(String num1, String num2) {
int len1 = num1.length();
int len2 = num2.length();
int[] res = new int[len1+len2];
for (int i = len1-1; i >= 0; i--) {
for (int j = len2-1; j >= 0; j--) {
int mul = (num1.charAt(i)-'0') * (num2.charAt(j)-'0');
int p1 = i+j, p2 = i+j+1;
int sum = mul + res[p2];
res[p1] += sum / 10;
res[p2] = sum % 10;
}
}
StringBuilder sb = new StringBuilder();
for (int i : res) {
if (sb.length() == 0 && i == 0) continue;
sb.append(i);
}
return sb.length() == 0 ? "0" : sb.toString();
}
}
您可以输入任意值进行测试。
阅读全文