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);

 

你可能感兴趣的:(数据结构/算法)