大整数相乘

题目来源牛客网 https://www.nowcoder.com/practice/0f0badf5f2204a6bb968b0955a82779e?tpId=90&tqId=30777&tPage=1&rp=1&ru=/ta/2018test&qru=/ta/2018test/question-ranking

题目描述

有两个用字符串表示的非常大的大整数,算出他们的乘积,也是用字符串表示。不能用系统自带的大整数类型。

输入描述:

空格分隔的两个字符串,代表输入的两个大整数

输出描述:

输入的乘积,用字符串表示

思路:颠倒字符串顺序,逐位相乘相加,计算进位,结果依次插入到StringBuilder对象的首部。

注意点:1.两个数相乘m*n,结果的位数不会超过m的位数(len(m))加上n的位数(len(n))。

2.使用长为(len(m)+len(n))的整型数组记录结果然后依次处理后插入StringBuilder对象sb中,多出来的0也会保存到StringBuilder对象中,要记得移除掉。

 1 import java.util.Scanner;
 2 
 3 public class BigMultiplication {
 4 
 5     public static void main(String[] args) {
 6         Scanner sc = new Scanner(System.in);
 7         
 8         StringBuilder num1 = new StringBuilder(sc.next()).reverse();
 9         StringBuilder num2 = new StringBuilder(sc.next()).reverse();
10         sc.close();
11         
12         //the length of result won't be greater than length of num1 plus length of num2
13         int[] result = new int[num1.length() + num2.length()];
14         
15         for(int i=0; i<num1.length(); i++) {
16             int a = num1.charAt(i) - '0';
17             for(int j=0; j<num2.length(); j++) {
18                 int b = num2.charAt(j) - '0';
19                 result[i+j] += a * b;
20             }
21         }
22         StringBuilder sb  = new StringBuilder();
23         int carry = 0;
24         for(int i=0; i<result.length; i++) {
25             sb.insert(0, result[i]%10);
26             //calculate carry
27             carry = result[i] /10 ;
28             //adding carry to the higher bit (The highest bit won't produce the carry) 
29             if(i<result.length-1) {
30                 result[i+1] += carry; 
31             }
32         }
33         //remove zeros which are at the beginning
34         while(sb.charAt(0)=='0') {
35             sb.deleteCharAt(0);
36         }
37 
38         System.out.println(sb.toString());
39     }
40 
41 }
原文地址:https://www.cnblogs.com/singular/p/10423250.html