http://poj.org/problem?id=1503
题意:
给出n个数,计算和。
思路:
基础的大整数加法题。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 #include<vector> 7 using namespace std; 8 9 const int maxn = 100 + 5; 10 11 char s[maxn][maxn]; 12 int num[maxn][maxn]; 13 int ans[maxn]; 14 int max_len; 15 int n; 16 17 int add() 18 { 19 int i; 20 int t = 0; 21 for (i = 0; i < max_len; i++) 22 { 23 int k = 0; 24 for (int j = 0; j < n; j++) 25 { 26 k += num[j][i]; 27 } 28 k += t; 29 ans[i] = k % 10; 30 t = k / 10; 31 } 32 while (t) 33 { 34 ans[i++] = t % 10; 35 t /= 10; 36 } 37 return i; 38 } 39 40 int main() 41 { 42 //freopen("D:\\txt.txt", "r", stdin); 43 n = 0; 44 max_len = 0; 45 memset(num, 0, sizeof(num)); 46 while (gets(s[n])) 47 { 48 if (!strcmp(s[n], "0")) break; 49 int len = strlen(s[n]); 50 max_len = max(max_len, len); 51 for (int i = len - 1; i >= 0; i--) 52 num[n][len - 1 - i] = s[n][i] - ‘0‘; 53 n++; 54 } 55 int cnt = add(); 56 for (int i = cnt - 1; i >= 0;i--) 57 printf("%d", ans[i]); 58 printf("\n"); 59 return 0; 60 }
时间: 2024-11-03 22:21:51