华为集招第三题:大数相乘

题目: 大数相乘

用两种方式实现:Java自带BigInteger;Java编程实现

package com.wxy.huawei;

import java.math.BigInteger;
import java.util.Scanner;

/**
 * Created by Kode on 2018/9/12.
 */
public class disanti {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.nextLine();
        String b = sc.nextLine();
        int[] aNum = stringToInts(a);
        int[] bNum = stringToInts(b);
        int[] bigNumberMultiply = bigNumberMultiply(aNum, bNum);
        for (int temp : bigNumberMultiply) {
            System.out.print(temp + " ");
        }
        BigInteger bigIntegerA = new BigInteger(a);
        BigInteger bigIntegerB = new BigInteger(b);
        BigInteger multiply = bigIntegerA.multiply(bigIntegerB);
        System.out.println(multiply);
    }

    public static int[] stringToInts(String str) {
        int[] res = new int[str.length()];
        for (int i = 0; i < res.length; i++) {
            res[i] = Integer.parseInt(str.substring(i, i + 1));
        }
        return res;
    }

    public static int[] bigNumberMultiply(int[] num1, int[] num2) {
        int[] result = new int[num1.length + num2.length];

        for (int i = 0; i < num1.length; i++) {
            for (int j = 0; j < num2.length; j++) {
                result[i + j + 1] += num1[i] * num2[j];
            }
        }
        for (int k = result.length - 1; k > 0; k--) {
            if (result[k] > 10) {
                result[k - 1] += result[k] / 10;
                result[k] %= 10;
            }
        }
        return result;
    }
}

说点什么

avatar
  Subscribe  
提醒

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部