java 两个大数相乘

 

分析见原博客,代码整理(注释加说明)如下:

https://blog.csdn.net/outsanding/article/details/79472376

package com.interview.algorithm;

public class Mutiply {
    public static String multiply(String num1, String num2){
        //把字符串转成char数组
        char chars1[] = num1.toCharArray();
        char chars2[] = num2.toCharArray();
        //声明存放结果和两个乘积的容器,注:一个数乘以一个数的结果长度必定小于或者等于这个两个数长度之和。

        int result[] = new int[chars1.length + chars2.length];
        int n1[] = new int[chars1.length];
        int n2[] = new int[chars2.length];


        //把char转换成int数组。
        for (int i = 0; i < chars1.length; i++) {
            n1[i] = chars1[i] - '0';
        }
        for (int j = 0; j < chars2.length; j++) {
            n2[j] = chars2[j] - '0';
        }
        //逐个相乘
        for (int i = 0; i < chars1.length; i++) {
            for (int j = 0; j < chars2.length; j++) {
                result[i + j] += n1[i] * n2[j];
            }
        }
        //从后往前满十进位
        for (int i = result.length - 1; i > 0; i--) {
            result[i - 1] += result[i] / 10;
            result[i] = result[i] % 10;
        }
        //转成string并返回,注意最后一位没有存储东西,要将最后一位去除
        String resultStr = "";
        for (int i = 0; i < result.length - 1; i++) {
            resultStr += "" + result[i];
        }
        return resultStr;
    }

    public static void main(String[] args) {
        System.out.println(multiply("123","4567"));
    }
}

附String和int类型的转换

String s = "123";
int n= 12;
String ss = String.valueOf(n);
int i = Integer.parseInt(s);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值