大数相乘

本文介绍了一种在Java中实现大数乘法的方法。通过字符数组进行逐位相乘,并处理进位,最终输出乘积。示例使用了两个较大的数字字符串进行演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.test;


public class Multiply
{
    public static void multiply(char a[], char b[])
    {
        int alen=a.length;
        int blen=b.length;


        int[] result = new int[alen + blen];


        for (int i = 0; i < alen + blen; i++)
            result[i] = 0;


        int resultCount=blen+alen-2;


        // 对齐逐位相乘
        for (int j = blen-1; j >= 0; j--)
        {
            int tempb=(int)(b[j]-'0');
            for (int i =alen - 1; i >= 0; i--)
            {
                int tempa=(int)(a[i]-'0');
                result[i + j + 1] += tempa * tempb;


                int carry = result[i+j+1] / 10;
                result[i+j+1] = result[i+j+1] % 10;
                if (carry > 0)
                {
                    result[i+j] += carry;
                }


            }
        }


        if(result[0]>0)
        {
            resultCount+=1;
        }


        System.out.print("乘积:");
        for (int j=0;j <=resultCount; j++) {
            System.out.print(result[j]);
        }
    }


    public static void main(String[] args) {
        //String str1 = "999";
        //String str2 = "999";


        String str1 = "23456789009877666555544444";
        String str2 = "34658743659843759437594387594387";


        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();


        System.out.println("乘数1:"+str1);
        System.out.println("乘数2:"+str2);
        multiply(s1, s2);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值