大数相加
发布时间:2020-12-14 04:03:03 所属栏目:大数据 来源:网络整理
导读:? ? ? ? ? ? ?对于int,long,int64而言有时对我们所需要的数字远远超过了他们的范围,所以我们用一个int型数组来储存这个特别大的数,而两个大数相加更需要这种思想。大数相加在acm题目中也是常用到。 ? ? ? ? ? ? 我先定义了两个字符数组str1,str2。他们
? ? ? ? ? ? ?对于int,long,int64而言有时对我们所需要的数字远远超过了他们的范围,所以我们用一个int型数组来储存这个特别大的数,而两个大数相加更需要这种思想。大数相加在acm题目中也是常用到。 ? ? ? ? ? ? 我先定义了两个字符数组str1,str2。他们的长度为20000。还有一个ans字整数组他是存储最后的和。下面看代码吧,思路很简单。 ? ? ? ? ? ? /** *大数加法 **/ #include<iostream> #include<string.h> using namespace std; char num1[20000]; char num2[20000]; int ans[20001]; void Roll(char *s) { int len = strlen(s); char temp; for(int i = 0; i < len/2;i++) { temp = s[i]; s[i] = s[len-1-i]; s[len-1-i] = temp; } } int main() { while(true) { cin>>num1>>num2; int len1,len2; len1 = strlen(num1); len2 = strlen(num2); Roll(num1); Roll(num2); int len = 0; if(len1<len2) { int temp = 0; for(int i = 0; i <len2;i++) { if(i<len1) { ans[len++] = (num1[i]-'0'+num2[i]-'0'+ temp)%10 ; temp = (num1[i]-'0'+num2[i]-'0'+temp)/10; } else { ans[len++] = (num1[i]+num2[i]-'0'+ temp)%10 ; temp = (num1[i]+num2[i]-'0'+temp)/10; } } if(temp!=0) ans[len++] = temp; } else { int temp = 0; for(int i = 0; i < len1;i++) { if(i<len2) { ans[len++] = (num1[i]-'0'+num2[i]-'0'+temp)%10; temp = (num1[i]-'0'+num2[i]-'0'+temp)/10; } else { ans[len++] = (num1[i] +num2[i]-'0'+temp)%10; temp = (num1[i] + num2[i]-'0'+temp)/10; } } if(temp!=0) ans[len++] = temp; } for(int i = len-1; i >= 0 ;i--) { cout<<ans[i]; } cout<<endl; } return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |