实现计算两超大整数的乘积

如“111111111111111”和“222222222222222”,输出乘积“24691358024691308641975308642”。
== 不使用Java中的BigInteger等类==

public class BigIntegerMultiplication {
    public static void main(String[] args) {
        System.out.println(IntegerMultiplication("111111111111111","222222222222222"));
    }
    public static String IntegerMultiplication(String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        int carry = 0;
        String strTemp = "";//存储每次分治结果
        String res = "";
        String jz="";//补0
        for (int i = 0; i < chars1.length; i++) {
            if(i!=0){
                jz+="0";
            }
            int temp = chars1[chars1.length - i - 1] - '0';
            strTemp="";
            for (int j = 0; j < chars2.length; j++) {
                int temp2 = temp * ((chars2[chars2.length - j - 1] - '0'));
                int temp3=temp2+carry;
                strTemp = temp3%10+""+strTemp;
                carry = temp3 > 10 ? temp3 / 10 : 0;
            }
            res = IntegerAdd(res,strTemp+jz);
        }
        return res;
    }

    public static String IntegerAdd(String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        String res = "";
        int carry = 0;//进位
        char[] chars3 = chars1.length >= chars2.length ? chars1 : chars2;
        char[] chars4 = chars3== chars1 ? chars2 : chars1;
        for (int i = 0; i < chars3.length; i++) {
            int temp = chars3[chars3.length - i - 1] - '0';
            int temp2=0;
            if(i<chars4.length) {
                temp2 =chars4[chars4.length - i - 1] - '0';
            }
            int temp3=temp+temp2;
            res = (temp3)%10 + carry +res;
            carry = (temp3) > 10 ? (temp3) / 10 : 0;
        }
        return res;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值