1. 程式人生 > >高精度加法

高精度加法

-- 題目 可能 逆序 如果 相加 clu color code

【題目描述】
求兩個不超過200位的非負整數的和。

【輸入】
有兩行,每行是一個不超過200位的非負整數,可能有多余的前導0。

【輸出】
一行,即相加後的結果。結果裏不能有多余的前導0,即如果結果是342,那麽就不能輸出為0342。

【輸入樣例】
22222222222222222222
33333333333333333333

【輸出樣例】
55555555555555555555
#include<iostream>  
#include<cstring>  
#include<string>  
using namespace std;  
char s1[210
],s2[210]; int a[210],b[210],c[210]; int main() { cin>>s1; cin>>s2; int i,j,lena,lenb,lenc,max,x; lena=strlen(s1); lenb=strlen(s2); for(i=0;i<=lena;i++) //逆序存儲於數組中 a[lena-i]=s1[i]-0; for(i=0;i<=lenb;i++) b[lenb-i]=s2[i]-0; x=0; //x用來進位 lenc
=1; while( (lenc<=lena) || (lenc<=lenb) ) { c[lenc]=a[lenc]+b[lenc]+x; x=c[lenc]/10; c[lenc]=c[lenc]%10; lenc++; } c[lenc]=x; //最後這個位也要進,別忘了 while(c[lenc]==0) //刪除前導零 lenc--; for(i=lenc;i>0;i--) //逆序輸出數組c cout<<c[i]; cout
<<endl; return 0; }

註意題目條件!輸入可能會有前導零!

高精度加法