標籤:style blog http color strong 資料
之前杭電上也做過a + b的高精度的題,不過這道題的區別是有多組資料。
之前做的時候開了3個字元數組a,b,c,在計算的時候還要比較a,b長度,短的那個還要加‘0‘,還設定了一個add來存放進位。
現在看來這種演算法確實很繁瑣。
而這次只用了兩個字元數組,一個放加數,一個放和。
相比之前程式更短小了,而且可讀性也提高了。
果然辦法都是逼出來的。
沒有了add,在判斷進位的時候就看那一位的ASCII碼是否>‘9‘,然後進位。
尤其需要注意的一點是可能會出現連續進位的情況,比如99999 + 1。解決的辦法就是用迴圈來控制。
One of the firstusers of BIT‘s new supercomputer was Chip Diller. He extended his explorationof powers of 3 to go from 0 to 333 and he explored taking various sums of thosenumbers.
``Thissupercomputer is great,‘‘ remarked Chip. ``I only wish Timothy were here to seethese results.‘‘ (Chip moved to a new apartment, once one became available onthe third floor of the Lemon Sky apartments on Third Street.)
Input
The input willconsist of at most 100 lines of text, each of which contains a singleVeryLongInteger. Each VeryLongInteger will be 100 or fewer characters inlength, and will only contain digits (no VeryLongInteger will be negative).
The final inputline will contain a single zero on a line by itself.
Output
Your programshould output the sum of the VeryLongIntegers given in the input.
Sample Input
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0
Sample Output
370370367037037036703703703670
AC代碼:
1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7 8 const int maxn = 100 + 20; 9 char Linteger[maxn];10 char Resault[maxn];11 12 void Reverse(char s[], int l);13 14 int main(void)15 {16 #ifdef LOCAL17 freopen("424in.txt", "r", stdin);18 #endif19 20 int i;21 memset(Resault, ‘0‘, sizeof(Resault));//將結果全部初始化為‘0‘22 while(gets(Linteger) && Linteger[0] != ‘0‘)23 {24 int l = strlen(Linteger);25 Reverse(Linteger, l);26 for(i = 0; i < l; ++i)27 {28 Resault[i] = Resault[i] + Linteger[i] - ‘0‘;29 if(Resault[i] > ‘9‘)30 {31 int j = i;32 while(Resault[j] > ‘9‘)//考慮連續進位的情況33 {34 Resault[j] -= 10;35 ++j;36 ++Resault[j];37 }38 }39 }40 }41 for(i = 119; i >= 0; --i)//輸出時忽略前置042 if(Resault[i] != ‘0‘)43 break;44 for(; i >= 0; --i)45 cout << Resault[i];46 cout << endl;47 return 0;48 }49 void Reverse(char s[], int l)//用來反轉數組,從個位開始加起50 {51 int i;52 char t;53 for(i = 0; i < l / 2; ++i)54 {55 t = s[i];56 s[i] = s[l - i -1];57 s[l - i -1] = t;58 }59 }代碼君