uva 424 Integer Inquiry

本文介绍了一个经典的编程竞赛题目UVA424 Integer Inquiry,该题要求实现高精度加法来处理非常大的整数求和问题。通过倒序存储和逐位相加的方式,有效解决了大数求和的挑战。

                     uva 424 Integer Inquiry


One 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.)

Input

The 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.

Output

Your program should output the sum of the VeryLongIntegers given in the input.

Sample Input

123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0

Sample Output

370370367037037036703703703670

题目大意:多个数求和,很大的数哦。

解题思路:高精度加法,注意进位,注意把字符当做数字处理要减去    '0'。


#include<stdio.h>
#include<string.h>
int main() {
	char s1[1000], s2[1000];
	char a[1000], b[1000];
	memset(s1, 0, sizeof(s1));
	memset(a, 0, sizeof(a));
	memset(b, 0, sizeof(b));
	gets(b);
	for (int i = strlen(b) - 1, j = 0; i >= 0; i--, j++) {     //倒序储存,从s[0]开始处理,更方便。
			s1[j] = b[i];
		}
	while (gets(a) != NULL && a[0] != 0) {
		memset(b, 0, sizeof(b));
		memset(s2, 0, sizeof(s2));
		int len = strlen(a);
		for (int i = len - 1, j = 0; i >= 0; i--, j++) {   //同上
			s2[j] = a[i];
		}
		if (strlen(s1) < strlen(s2)) {   //找出位数更大的数
			strcpy(b, s1);
			strcpy(s1, s2);
			strcpy(s2, b);
		}
		for (int i = 0; i < strlen(s2); i++) {     //先逐位相加
			s1[i] += s2[i] - '0';
		}	
		for (int i = 0; i < strlen(s1) - 1; i++) {   //然后大于9的位,进一
			if (s1[i] > '9') {
				s1[i] -= 10;
				s1[i+1]++;
			}
		}
	if (s1[strlen(s1) - 1] > '9') {   //处理最高位
		s1[strlen(s1) - 1] -= 10;
		s1[strlen(s1)] = '1';
	}
	}
	for (int i = strlen(s1) - 1; i >= 0; i--) {   //再倒序输出
		printf("%c", s1[i]);
	}
	printf("\n");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值