Problem Description I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
2 1 2 112233445566778899 998877665544332211
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
分析:對於此題做法有兩種:其一,使2字符串的中的字符數字減去'0',逐個相加大於等於10的可以使本位減10,下一位自增1,後面的處理就非常簡單了;其二,便是讀入字符串後先讓各個字符減'0',一一對應存入整形數組中;之後再相加。對於2種方法大致是相同的,都要從後面向前加,逢十進位,以及數組初始化均要初始為0,一邊方便運算。
#include#include #include char a[1001]; //開辟兩個字符數組a、b,作為兩個輸入的大數 char b[1001]; char c[1002]; int main(void) { int carry = 0, n, j; int lena, lenb, i, lenc; scanf(%d, &n); for(j = 1; j <= n; j++) { memset(a, 0, 1001); memset(b, 0, 1001); memset(c, 0, 1002); scanf(%s, a); scanf(%s, b); lena = strlen(a); lenb = strlen(b); for(lena--, lenb--, i = 0, carry = 0; (lena >= 0) && (lenb >= 0); lena--, lenb--, i++) { c[i] = a[lena]-'0' + b[lenb]-'0' + carry; if((int)c[i] > 9) { c[i] = c[i] - 10 + '0'; carry = 1; } else { c[i] += '0'; carry = 0; } } while(lena >= 0) { c[i] = c[i] + a[lena] + carry; //有可能加上carry後還可以向前進位 if(c[i] > '9') { c[i] -= 10; carry = 1; } else carry = 0; i++; lena--; } while(lenb >= 0) { c[i] = c[i] + b[lenb] + carry; if(c[i] > '9') { c[i] -= 10; carry = 1; } else carry = 0; i++; lenb--; } lenc = strlen(c); printf(Case %d: , j); printf(%s + %s = , a, b); for(i = lenc-1; i >= 0; i--) //c數組中c[0]存放的是大數的最低位,c[lenc-1]存放的是大數的最高位 printf(%c, c[i]); printf( ); if(j != n) printf( ); } return 0; }