您的位置:首页 > 产品设计 > UI/UE

POJ-1503-Integer Inquiry-大数加法

2012-09-12 00:01 501 查看
DescriptionOne of the first users of BIT's new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers. ``This supercomputer is great,'' remarked Chip. ``I only wish Timothy were here to see these results.'' (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.) InputThe input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative). The final input line will contain a single zero on a line by itself. OutputYour program should output the sum of the VeryLongIntegers given in the input.Sample Input1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900Sample Output370370367037037036703703703670

#include <iostream>

#include <string>using namespace std;char* Reverse(char *num){ int len = strlen(num); for(int i = 0; i < len/2; i++) { int temp = num[i]; num[i] = num[len-i-1]; num[len-i-1] = temp; } return num;}char* sum(char num1[], char num2[]){ int len1 = strlen(num1); int len2 = strlen(num2); int len = len1 < len2 ? len1 : len2; int temp = 0; int flag = 0; for(int i = 0; i < len; i++) { temp = (num1[i]-'0')+(num2[i]-'0'); if(flag != 0) { temp++; flag = 0; } if(temp >= 10) { num1[i] = temp%10 + '0'; flag = 1; } else { num1[i] = temp + '0'; flag = 0; } } if(len1 == len2) { if(flag != 0) { num1[len1] = '1'; num1[len1+1] = '\0'; } else num1[len1] = '\0'; } if(len1 > len2) { for(int i = len2; i < len1; i++) { temp = num1[i]-'0'; if(flag != 0) { temp++; flag = 0; } if(temp >= 10) { num1[i] = temp%10 + '0'; flag = 1; } else { num1[i] = temp + '0'; flag = 0; } } if(flag != 0) { num1[len1] = '1'; num1[len1+1] = '\0'; } else num1[len1] = '\0'; } if(len2 > len1) { for(int i = len1; i < len2; i++) { temp = num2[i]-'0'; if(flag != 0) { temp++; flag = 0; } if(temp >= 10) { num1[i] = temp%10 + '0'; flag = 1; } else { num1[i] = temp + '0'; flag = 0; } } if(flag != 0) { num1[len2] = '1'; num1[len2+1] = '\0'; } else num1[len2] = '\0'; } return num1;}int main(){ char *s[101]; int i = 0; while(1) { s[i] = (char*)malloc(sizeof(char*)*101); memset(s[i], 0, 101); cin.getline(s[i], 101, '\n'); if(strcmp(s[i], "0") == 0) break; i++; } if(i == 1) { cout << s[0] << endl; return 1; } for(int j = 0; j < i; j++) Reverse(s[j]); char *b; b = (char*)malloc(sizeof(105)); memset(b, 0, 105); b = sum(s[0], s[1]); for(int j = 2; j < i; j++) b = sum(b, s[j]); int len = strlen(b); for(int i = len-1; i >= 0; i--) cout << b[i]; system("pause"); return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: