package com.zjp.offer.study; import java.util.Scanner; /** * 大整数相乘: * 有两个用字符串表示的非常大的大整数,算出他们的乘积,也是用字符串表示。 * 不能用系统自带的大整数类型。 */ public class BigIntProduct { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str1 = sc.next(); String str2 = sc.next(); String res = bigIntProduct(str1, str2); System.out.println(res); } private static String bigIntProduct(String str1, String str2) { //转换为char型数组 char[] char1 = str1.toCharArray(); char[] char2 = str2.toCharArray(); //转换为int数组 int[] arr1 = new int[char1.length]; int[] arr2 = new int[char2.length]; for (int i = 0; i < char1.length; i++) { arr1[char1.length - 1 - i] = char1[i] - '0'; } for (int i = 0; i < char2.length; i++) { arr2[char2.length - 1 - i] = char2[i] - '0'; } //用于存放结果 int[] res = new int[char1.length + char2.length]; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr2.length; j++) { res[i + j] += arr1[i] * arr2[j]; if (res[i + j] >= 10) { res[i + j + 1] += res[i + j] / 10; res[i + j] = res[i + j] % 10; } } } //将结果转换为字符串 StringBuilder sb = new StringBuilder(); for (int i = res.length - 1; i >= 0; i--) { //高位为0,忽略 if (i == res.length - 1 && res[i] == 0) { continue; } sb.append(res[i]); } return sb.toString(); } }
java笔试题-大整数相乘
最新推荐文章于 2021-07-14 10:00:14 发布