结果超过Int类型最大容量,如何实现运算及存储

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值