Tile:HDOJ 1002 -- sum of large numbers
part one: thinkinga. Character arrays catch large numbers, attaching the numeric strings to corresponding Integer arrays(the bond arrays should be in reverse order); To get the final two equal length large number storing in integer arrays, we fill zeros in the upper positions for the smaller one.part two: codes
b. Adding each number of integer arrays coming from step a with carry, please note whether the last carry exists or not.
c. Last but not least, we must output the outputs strictly as requested.
See below!
1.思路
a. 字符数组接收大数,大数字符串转化为对应的int类型数组(注意字符数组和对应的整型数组应该是逆序的);对较短的大数高位填充0,得到两个长度相同的大数整型数组。
b. 大数所在的int类型数组逐位依次相加(该进位的要进位),根据最后一步累加结果是否进位决定最终求和结果。
c. 严格按照命题格式要求输出结果。
2.代码明细
<span style="font-size:14px;">#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int n, m; char a[1001], b[1001]; int ai[1001], bi[1001], ci[1001]; int alen, blen, clen, maxlen, minlen; int i, j, temp; int num; scanf("%d", &n); m = n; while(m --) { scanf("%s%s", &a, &b); alen = strlen(a); blen = strlen(b); if(alen > blen) { maxlen = alen; minlen = blen; for(i = 0; i < alen; ++ i) { ai[i] = a[alen - 1 - i] - '0'; if(i < blen) { bi[i] = b[blen - 1 - i] - '0'; } else { bi[i] = 0; } } } else { maxlen = blen; minlen = alen; for(i = 0; i < blen; ++ i) { bi[i] = b[blen - 1 - i] - '0'; if(i < alen) { ai[i] = a[alen - 1 - i] - '0'; } else { ai[i] = 0; } } } j = 0; for(i = 0; i < maxlen; ++ i) { temp = ai[i] + bi[i] + j; ci[i] = temp % 10; j = temp / 10; } if(j > 0) { ci[maxlen] = j; clen = maxlen + 1; } else { clen = maxlen; } num = n - m; printf("Case %d:\n", num); printf("%s + %s = ", a, b); for(i = clen - 1; i >= 0; -- i) printf("%d", ci[i]); if(num < n) { printf("\n\n"); } else { printf("\n"); } } return 0; }</span>