俩个大数相乘(java实现)

package com.example;

/**
 *
 * @author ZHANGHAOHAO089
 * @date 2017/6/27
 */

public class BigNumber {

    public static void main(String args[]) {
        String str1 = "121255";
        String str2 = "23545";
        char[] data1 = str1.toCharArray();
        char[] data2 = str2.toCharArray();
        convert(data1);
        convert(data2);
        multiply(data1, data2);
    }

    //高低位对调
    public static void convert(char data[]) {
        int len = data.length;
        for (int i = 0; i < len / 2; i++) {
            char num = data[len - i - 1];
            data[len - i - 1] = data[i];
            data[i] = num;
        }
    }

    public static void multiply(char[] x, char[] y) {
        int lenX = x.length;
        int lenY = y.length;
        int[] sum = new int[lenX + lenY + 3];//最多是这个位数
        //对sum赋值
        for (int i = 0; i < sum.length; i++) {
            sum[i] = 0;
        }
        for (int i = 0; i < lenX; i++) {
            for (int j = 0; j < lenY; j++) {
                sum[i + j] += Integer.parseInt(String.valueOf(x[i])) * Integer.parseInt(String.valueOf(y[j]));
            }
        }
        //高低位进阶
        for (int m = 0; m < sum.length; m++) {
            int number = sum[m] / 10;
            if (number > 0) {
                sum[m] = sum[m] % 10;
                sum[m + 1] += number;
            }
        }

        //打印
        int index = 0;
        for (int n = sum.length - 1; n > 0; n--) {
            if (sum[n] > 0) {
                index = n;
                break;
            }
        }

        for (int m = index; m >= 0; m--) {
            System.out.print(sum[m]);
        }
    }
}

核心就是转化为数组来实现相乘,而且sum[i+j]的数是关键

你可能感兴趣的:(java算法)