代码:
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int maxn = 1000; int a[maxn],b[maxn]; int main(){ string s1,s2; cin>>s1>>s2; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); int len1= s1.length(); int len2 = s2.length(); for(int i=0;i<len1;i++){ a[len1-i] = s1[i]-'0'; } for(int i=0;i<len2;i++){ b[len2-i] = s2[i]-'0'; } int i=1; while(i<=len1||i<=len2){ if(a[i]<b[i]){ a[i+1]--; a[i]=a[i]+10; } a[i] = a[i]-b[i]; i++; } int j; for(j=len1;j>=1;j--){ if(a[j]) break; } for(int k = j;k>=1;k--){ cout<<a[k]; } cout<<endl; return 0; }
大数相加:
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int maxn = 1000; int a[maxn],b[maxn]; int c[maxn]; int main(){ string s1,s2; cin>>s1>>s2; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(c,0,sizeof(c)); int len1= s1.length(); int len2 = s2.length(); for(int i=0;i<len1;i++){ a[len1-i] = s1[i]-'0'; } for(int i=0;i<len2;i++){ b[len2-i] = s2[i]-'0'; } int i=1; int t = 0; while(i<=len1||i<=len2){ t += a[i]+b[i]; c[i] = t%10; t = t/10; i++; } if(t){ c[i] = t; } else{ i--; } for(int j = i;j>=1;j--){ cout<<c[j]; } cout<<endl; return 0; }