UVa 424 Integer Inquiry

之前杭电上也做过a + b的高精度的题,不过这道题的区别是有多组数据。

之前做的时候开了3个字符数组a,b,c,在计算的时候还要比较a,b长度,短的那个还要加'0',还设置了一个add来存放进位。

现在看来这种算法确实很繁琐。

而这次只用了两个字符数组,一个放加数,一个放和。

相比之前程序更短小了,而且可读性也提高了。

果然办法都是逼出来的。

没有了add,在判断进位的时候就看那一位的ASCII码是否>'9',然后进位。

尤其需要注意的一点是可能会出现连续进位的情况,比如99999 + 1。解决的办法就是用循环来控制。


One of the firstusers of BIT's new supercomputer was Chip Diller. He extended his explorationof powers of 3 to go from 0 to 333 and he explored taking various sums of thosenumbers.

``Thissupercomputer is great,'' remarked Chip. ``I only wish Timothy were here to seethese results.'' (Chip moved to a new apartment, once one became available onthe third floor of the Lemon Sky apartments on Third Street.)

Input

The input willconsist of at most 100 lines of text, each of which contains a singleVeryLongInteger. Each VeryLongInteger will be 100 or fewer characters inlength, and will only contain digits (no VeryLongInteger will be negative).

The final inputline will contain a single zero on a line by itself.

Output

Your programshould output the sum of the VeryLongIntegers given in the input.

Sample Input

123456789012345678901234567890

123456789012345678901234567890

123456789012345678901234567890

0

Sample Output

370370367037037036703703703670


AC代码:

//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 100 + 20;
char Linteger[maxn];
char Resault[maxn];

void Reverse(char s[], int l);

int main(void)
{
	#ifdef LOCAL
		freopen("424in.txt", "r", stdin);
	#endif

	int i;
	memset(Resault, '0', sizeof(Resault));//将结果全部初始化为'0'
	while(gets(Linteger) && Linteger[0] != '0')
	{
		int l = strlen(Linteger);
		Reverse(Linteger, l);
		for(i = 0; i < l; ++i)
		{
			Resault[i] =  Resault[i] + Linteger[i] - '0';
			if(Resault[i] > '9')
			{
				int j = i;
				while(Resault[j] > '9')//考虑连续进位的情况
				{
					Resault[j] -= 10;
					++j;
					++Resault[j];
				}
			}
		}
	}
	for(i = 119; i >= 0; --i)//输出时忽略前导0
		if(Resault[i] != '0')
			break;
	for(; i >= 0; --i)
		cout << Resault[i];
	cout << endl;
	return 0;
}
void Reverse(char s[], int l)//用来反转数组,从个位开始加起
{
	int i;
	char t;
	for(i = 0; i < l / 2; ++i)
	{
		t = s[i];
		s[i] = s[l - i -1];
		s[l - i -1] = t;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值