您的位置:首页 > 其它

蓝桥杯算法提高 ADV-197 大数乘法 题解

2018-03-24 16:52 441 查看
题目:

当两个比较大的整数相乘时,可能会出现数据溢出的情形。为避免溢出,可以采用字符串的方法来实现两个大数之间的乘法。具体来说,首先以字符串的形式输入两个整数,每个整数的长度不会超过8位,然后把它们相乘的结果存储在另一个字符串当中(长度不会超过16位),最后把这个字符串打印出来。例如,假设用户输入为:62773417和12345678,则输出结果为:774980393241726.

输入:

  62773417 12345678

输出:

  774980393241726

思路:

借鉴了蓝桥杯真题填空题,具体思路移步这里:

大数乘法

跟上面填空题不同的几点:

数据更大

判断有无为0的情况

Code:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <fstream>
using namespace std;
const int maxn = 50;

void multi(int a, int b, long long *res){
long long base = 10000000000;
long long x1 = a % base;
long long x2 = a / base;
long long y1 = b % base;
long long y2 = b / base;

long long n1 = x1 * y1;
long long n2 = x2 * y1;
long long n3 = x1 * y2;
long long n4 = x2 * y2;

res[3] = n1 % base;
res[2] = n1 / base + n2 % base + n3 % base;
res[1] = n2 / base + n3 / base + n4 % base;
res[0] = n4 / base;

res[2] += res[3] / base;
res[3] = res[3] % base;
res[1] += res[2] / base;
res[2] = res[2] % base;
res[0] += res[1] / base;
res[1] = res[1] % base;

}

int main(){
//  fstream cin("a.txt");
char s1[10],s2[10];
long long res[4] = {0,0,0,0};

cin>>s1>>s2;

int a = atoi(s1);
int b = atoi(s2);

multi(a,b,res);
if(a == 0 || b == 0){
cout<<"0"<<endl;
return 0;
}
int i = 0;
while(res[i] == 0) ++i;
for(i; i < 4; ++i){
cout<<res[i];
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: