题目地址:http://ac.jobdu.com/problem.php?pid=1198
- 题目描述:
-
实现一个加法器,使其能够输出a+b的值。
- 输入:
-
输入包括两个数a和b,其中a和b的位数不超过1000位。
- 输出:
-
可能有多组测试数据,对于每组数据,
输出a+b的值。
- 样例输入:
-
2 6 10000000000000000000 10000000000000000000000000000000
- 样例输出:
-
8 10000000000010000000000000000000
#include <stdio.h> #include <string.h> typedef struct biginteger{ int digit[1000]; int size; }BigInteger; void StrToInt (char str[], BigInteger * big){ int len = strlen (str); int a, b, c, d, i, j; i = 0; while (len >= 4){ a = str[len - 4] - '0'; b = str[len - 3] - '0'; c = str[len - 2] - '0'; d = str[len - 1] - '0'; big->digit[i] = a * 1000 + b * 100 + c * 10 + d; len -= 4; ++i; } if (len > 0){ big->digit[i] = 0; for (j=0; j<len; ++j){ big->digit[i] = big->digit[i] * 10 + str[j] - '0'; } ++i; } big->size = i; } void Add (BigInteger * a, BigInteger * b){ int carry = 0; int sum = 0; int len = (a->size > b->size) ? a->size : b->size; int i; for (i=0; i<len; ++i){ sum = a->digit[i] + b->digit[i] + carry; carry = sum / 10000; a->digit[i] = sum % 10000; } if (carry > 0){ a->digit[i] = carry; a->size = i + 1; } else{ if (a->size < b->size) a->size = b->size; } } int main(void){ BigInteger a, b; char str1[1001], str2[1001]; int index; while (scanf ("%s%s", str1, str2) != EOF){ memset (a.digit, 0, sizeof(a.digit)); memset (b.digit, 0, sizeof(b.digit)); a.size = b.size = 0; StrToInt (str1, &a); StrToInt (str2, &b); Add (&a, &b); index = a.size - 1; printf ("%d", a.digit[index]); --index; while (index >= 0){ printf ("%04d", a.digit[index]); --index; } putchar (' '); } return 0; }