UVa 424 Integer Inquiry
之前杭电上也做过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.)
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.
Your programshould output the sum of the VeryLongIntegers given in the input.
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0
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 LOCAL 17 freopen("424in.txt", "r", stdin); 18 #endif 19 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)//输出时忽略前导0 42 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 }