九度 題目1198:a+b
原題OJ鏈接:http://ac.jobdu.com/problem.php?pid=1198
題目描述:
實現一個加法器,使其能夠輸出a+b的值。
輸入:
輸入包括兩個數a和b,其中a和b的位數不超過1000位。
輸出:
可能有多組測試數據,對於每組數據,
輸出a+b的值。
樣例輸入:
2 6
10000000000000000000 10000000000000000000000000000000
樣例輸出:
8
10000000000010000000000000000000
解題思路:
利用結構體 struct bigInteger{int digit[1050];int size;};
來保存一個高精度整數。其中,digit數組用來保存大整數中每若干位的數字,我們在這裏使用每4位爲一個單位保存,size爲digit數組中已經使用過的位數。以整數123456789爲例,則digit[0]=6789; digit[1]=2345;digit[2]=1;size=3 。
模擬加法運算法則,按照從低位開始 各對應位相加並加上來自低位的進位從而獲得本位的數值。
源代碼:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct bigInteger{
int digit[1050];
int size;
};
bigInteger input(string str){//將字符串轉化爲整數存儲到bigInteger結構體中
int len=str.length();
int base[4]={1,10,100,1000};
bigInteger N;
N.size=0;
memset(N.digit,0,sizeof(N.digit));
int strpos,digpos;
for(strpos=len-1,digpos=0;strpos>=0;strpos=strpos-4,digpos++){
int tmp=0;
for(int i=0;i<4;i++){
if((strpos-i)>=0){
tmp=tmp+(str[strpos-i]-'0')*base[i]; //每4位分別乘以1,10,100,1000
}
}
N.digit[digpos]=tmp;
N.size++;
}
return N;
}
void output(bigInteger a,bigInteger b){//兩個bigInteger結構體相加並輸出結果
int asize=a.size,bsize=b.size;
int SIZE=max(asize,bsize);//取兩個大整數的最大的位數
bigInteger c;
c.size=0;
memset(c.digit,0,sizeof(c.digit)); //初始化 大整數c
int carry=0;
int tmp;
for(int i=0;i<SIZE;i++){
tmp=a.digit[i]+b.digit[i]+carry;
carry=0;
if(tmp>=10000){
carry=tmp/10000; //carry爲進位
}
c.digit[i]=tmp%10000;
c.size++;
}
if(carry!=0){
c.digit[c.size]=carry; //假如最後的進位的那一位,超出了SIZE-1
c.size++;
}
cout<<c.digit[c.size-1]; //首先輸出最高位
for(int i=c.size-2;i>=0;i--){
if(c.digit[i]>=1000) cout<<c.digit[i];
else if(c.digit[i]>=100) cout<<0<<c.digit[i];
else if(c.digit[i]>=10) cout<<0<<0<<c.digit[i];
else cout<<0<<0<<0<<c.digit[i];
}
cout<<endl;
return;
}
int main(){
string str1,str2;
while(cin>>str1>>str2){
bigInteger a=input(str1);
bigInteger b=input(str2);
output(a,b);
}
return 0;
}