package com.micah.chapter01;
import java.math.BigInteger;
/**
* @Author m.kong
* @Date 2021/7/4 上午9:22
* @Version 1
* @Description
*/
public class Q43 {
/**
* 方法1
* @param num1 操作数1
* @param num2 操作数2
*/
public static void multiply1(String num1, String num2) {
BigInteger a = new BigInteger(num1);
BigInteger b = new BigInteger(num2);
System.out.println("a * b = " + a.multiply(b));
System.out.println("a + b = " + a.add(b));
System.out.println("a / b = " + a.divide(b));
System.out.println("a - b = " + a.subtract(b));
}
/**
* 对超大数进行数学运算,使用字符串进行操作
* @param num1 操作数1
* @param num2 操作数2
* @return 操作值
*/
public static String multiply2(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
int m = num1.length(), n = num2.length();
int[] ansArr = new int[m + n];
for (int i = m - 1; i >= 0; i--) {
int x = num1.charAt(i) - '0';
for (int j = n - 1; j >= 0; j--) {
int y = num2.charAt(j) - '0';
ansArr[i + j + 1] += x * y;
}
}
for (int i = m + n - 1; i > 0; i--) {
ansArr[i - 1] += ansArr[i] / 10;
ansArr[i] %= 10;
}
int index = ansArr[0] == 0 ? 1 : 0;
StringBuffer ans = new StringBuffer();
while (index < m + n) {
ans.append(ansArr[index]);
index++;
}
return ans.toString();
}
public static void main(String[] args) {
System.out.println("int capacity:" + Integer.MIN_VALUE + " - " + Integer.MAX_VALUE);
System.out.println("long capacity:" + Long.MIN_VALUE + " - " + Long.MAX_VALUE);
multiply1("123456789","987654321");
System.out.println(multiply2("123456789", "987654321"));
}
}
演示结果:
int capacity:-2147483648 - 2147483647
long capacity:-9223372036854775808 - 9223372036854775807
a * b = 121932631112635269
a + b = 1111111110
a / b = 0
a - b = -864197532
121932631112635269
Process finished with exit code 0