首页 > 其他 > 详细

拼多多笔试:大整数相乘

时间:2019-07-27 19:17:41      阅读:114      评论:0      收藏:0      [点我收藏+]

题目描述:

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

 

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

输出描述:
输入的乘积,用字符串表示

示例1

输入:

72106547548473106236 982161082972751393

输出:

70820244829634538040848656466105986748

 

思路分析:

一道字符串相关的题。由于最高位可能存在进位,需要将两个字符串倒序,进行相乘,来判断进位。乘积的最大长度是不会超过两个字符串的长度和。还有就是这里没有输入负数的情况。

 

代码:

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<limits.h>
 4 #include<stdlib.h>
 5 #include<string>
 6 #include<vector>
 7 using namespace std;
 8 
 9 string mul(string s1, string s2)
10 {
11     vector<int> num1, num2;
12     int len1 = s1.length(), len2 = s2.length();
13     string s;
14     vector<int> num(len1+len2,0);
15     for(int i = len1-1; i>=0; i--)
16         num1.push_back(s1[i]-0);
17     for(int i=len2-1; i>=0; i--)
18         num2.push_back(s2[i]-0);
19     for(int i=0; i<len1; i++)
20     {
21         for(int j=0; j<len2; j++)
22         {
23             num[i+j] += num1[i]*num2[j];
24         }
25     }
26     for(int i = 0; i<len1+len2-1; i++)
27     {
28         num[i+1] += num[i]/10;
29         num[i] = num[i]%10;
30     }
31     if(num[len1+len2-1])
32         s += num[len1+len2-1]+0;
33     for(int i = len1+len2-2; i>=0; i--)
34         s += num[i]+0;
35     return s;
36 }
37 int main()
38 {
39     string str1, str2;
40     while(cin>>str1>>str2)
41     {
42         string s;
43         s = mul(str1, str2);
44         cout<<s<<endl;
45     }
46     return 0;
47 }

 

拼多多笔试:大整数相乘

原文:https://www.cnblogs.com/LJ-LJ/p/11256246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!