突然心血来潮,拿着大整数来消遣了一下。
第一种方法:
讲字符数组一一对应的转换到整型数组中,然后进行相加运算
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define M 1000
char str1[M+10], str2[M+10];
int num1[M+10], num2[M+10], num[M+10];
int Plus(){
int len = MAX(strlen(str1), strlen(str2));
for(int i=1; i<=len; ++i){
num[i] = num[i-1]/10+num1[i]+num2[i];
num[i-1] %= 10;
}
}
int main(){
while(~scanf("%s%s", str1, str2)){
int len;
memset(num1,0,sizeof(num1));
memset(num2,0,sizeof(num2));
len = strlen(str1);
for(int i=0; i<len; ++i){
num1[len-i] = str1[i]-'0';
}
len = strlen(str2);
for(int i=0; i<len; ++i){
num2[len-i] = str2[i]-'0';
}
Plus();
int i=M+10;
int len = MAX(strlen(str1), strlen(str2));
for(int j=i; j>0; --j)
printf("%d", num[j]);
printf("\n");
}
return 0;
}
第二种方法:
将数据压缩写入整型数组中,每4位写入一个数组中。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define M 1000
char str1[M+10], str2[M+10];
int num1[M+10], num2[M+10], num[M+10];
int Plus(){
int len = MAX((strlen(str1)/4),(strlen(str2)/4))+1;
for(int i=1; i<=len; ++i){
num[i] = num[i-1]/10000+num1[i]+num2[i];
num[i-1] %= 10000;
}
}
int main(){
while(~scanf("%s%s", str1, str2)){
memset(num1, 0, sizeof(num1));
memset(num2, 0, sizeof(num2));
int len = strlen(str1);
int i,j;
for(i=len-1,j=1; i>=3; i-=4){
for(int k=3; k>=0; --k)
num1[j] = (str1[i-k]-'0')+num1[j]*10;
j++;
}
if(i==0)
num1[j] = str1[i]-'0';
else if(i==1)
num1[j] = (str1[i-1]-'0')*10+str1[i]-'0';
else if(i==2)
num1[j] = ((str1[i-2]-'0')*10+str1[i-1]-'0')*10+str1[i]-'0';
len = strlen(str2);
for(i=len-1,j=1; i>=3; i-=4){
for(int k=3; k>=0; --k)
num2[j] = (str2[i-k]-'0')+num2[j]*10;
j++;
}
if(i==0)
num2[j] = str2[i]-'0';
else if(i==1)
num2[j] = (str2[i-1]-'0')*10+str2[i]-'0';
else if(i==2)
num2[j] = ((str2[i-2]-'0')*10+str2[i-1]-'0')*10+str2[i]-'0';
Plus();
len = MAX((strlen(str1)/4),(strlen(str2)/4))+1;
printf("%d", num[len]);
for(i = len-1; i>0; --i){
printf("%04d", num[i]);
}
printf("\n");
}
return 0;
}
如有哪里有问题,请留言!