1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| #include<bits/stdc++.h>
void add(int* count_1,int *count_2,int *ans,int max) { for(int now=0;now<max;now++) { ans[now]+=count_1[now]+count_2[now]; if(ans[now]>=10) { ans[now+1]+=1; ans[now]%=10; } } }
void sub(int* count_1,int *count_2,int *ans,int max) { for(int now=0;now<max;now++) { ans[now]+=count_1[now]-count_2[now]; if(ans[now]<0) { ans[now]+=10; ans[now+1]--; } } }
void print(int *ans,int max) { bool kg=false; for(int now=max-1;now>=0;now--) { if(ans[now]!=0||kg==true) { printf("%d",ans[now]); kg=true; } } }
int main() { char string0[1000],*front,*after,sign; scanf("%s",string0); for(int now=0;;now++) { if(string0[now]=='+') { sign='+'; front=strtok_r(string0,"+",&after); break; } else if(string0[now]=='-') { sign='-'; front=strtok_r(string0,"-",&after); break; } } int n=strlen(front),m=strlen(after); int max; if(n>m) { max=n+1; } else { max=m+1; } int count_1[max], count_2[max], ans[max]; memset(count_1,0,sizeof(count_1)); memset(count_2,0,sizeof(count_2)); memset(ans,0,sizeof(ans));
for(int now=0;now<n;now++) { count_1[now]=front[n-now-1]-'0'; } for(int now=0;now<m;now++) { count_2[now]=after[m-now-1]-'0'; }
printf(" = "); if(sign=='+') { add(count_1,count_2,ans,max); } else { if(n>m) { sub(count_1,count_2,ans,max); } else if(n==m) { bool state=false; for(int a=max-1;a>=0&&state==false;a--) { if(count_1[a]>count_2[a]) { sub(count_1,count_2,ans,max); state=true; } else if(count_1[a]<count_2[a]) { printf("-"); sub(count_2,count_1,ans,max); state=true; } } if(state==false) { printf("0"); } } else { printf("-"); sub(count_2,count_1,ans,max); } } print(ans,max); return 0; }
|