二、大数相减
//大数相减 #include <cstdio> #include <cstring> #include <string> #include <iostream> #include <cmath> #include <algorithm> using namespace std; int x[100]={0},y[100]={0},z[100]={0}; void sub(int x[],int y[],int len) { for(int i=0;i<len;i++) { if(x[i]>=y[i]) z[i]=x[i]-y[i]; else if(x[i]<y[i]) { z[i]=x[i]+10-y[i]; x[i+1]=x[i+1]-1; } } for(int i=len-1;i>0;i--) { if(z[i]==0) len--; else break; } for(int i=len-1;i>=0;i--) cout<<z[i]; cout<<endl; } int main() { char chr1[100],chr2[100]; int len1,len2; while(scanf("%s %s",chr1,chr2)) { int i,j=0,k=0; len1=strlen(chr1); len2=strlen(chr2); for(i=len1-1,j=0;i>=0;i--) x[j++]=chr1[i]-'0'; for(i=len2-1,k=0;i>=0;i--) y[k++]=chr2[i]-'0'; if(len1>len2) sub(x,y,len1); else if(len1<len2) { printf("-"); sub(y,x,len2); } else if(len1==len2) { for(i=len1-1;i>=0;i--) { if(x[i]==y[i]) continue; else if(x[i]>y[i]) { sub(x,y,len1); break; } else if(x[i]<y[i]) { printf("-"); sub(y,x,len1); break; } } if(i==-1) sub(x,y,len1); } } return 0; }
一、大数相加
#include <cstdio> #include <cstring> #include <string> #include <iostream> #include <cmath> #include <algorithm> using namespace std; int main() { char chr1[100],chr2[100]; int a[100]={0},b[100]={0},c[100]={0}; int len1,len2,len; while(scanf("%s %s",chr1,chr2)) { int i,j=0,k=0; len1=strlen(chr1); len2=strlen(chr2); for(i=len1-1;i>=0;i--) { a[j]=chr1[i]-'0'; j++; } for(i=len2-1;i>=0;i--) { b[k]=chr2[i]-'0'; k++; } if(len1>len2) len=len1; else len=len2; int m=0; for(i=0;i<len;i++) { c[i]=(a[i]+b[i]+m)%10; if(a[i]+b[i]+m>=10) m=1; else m=0; } if(a[i-1]+b[i-1]+m>10) c[i]=1; else i=i-1; for(;i>=0;i--) cout<<c[i]; cout<<endl; } return 0; }