HDU 1047 Integer Inquiry

/*
题意:输入一些大整数,输出它们之和

在这道题中找到了一个重大的出错原因,即①处的初始化
*/
#include <cstdio>
#include <cstring>
const int nMax = 200;
struct BigNumber
{
	int data[nMax];
	int len;
	BigNumber(){len = 1; memset(data, 0, sizeof(data));}
	BigNumber(char *str){*this = str;}
	BigNumber & operator=(char *str);
	BigNumber operator+(BigNumber &a);
	void clearLeadZero();
	void print();
};
BigNumber & BigNumber::operator=(char *str)
{
	memset(data,0,sizeof(data));//①最新补充,如果你想将剩余部分都设置为零,则需要增加该语句!
	len = strlen(str);
	int i;
	for(i = 0; i < len; ++ i)
		data[i] = str[len - i - 1] - '0';
	return *this;
}
BigNumber BigNumber::operator+(BigNumber &a)
{
	int q = 0;
	int i, j;
	BigNumber z;
	for(i = 0, j = 0;q || i < len || j < a.len; ++ i, ++ j)
	{
		int p = data[i] + a.data[j] + q;
		z.data[i] = p % 10;
		q = p / 10;
	}
	z.len = i;
	z.clearLeadZero();
	return z;
}
void BigNumber::clearLeadZero()
{
	while(len > 1 && !data[len - 1]) -- len;
}
void BigNumber::print()
{
	int i;
	for(i = len -1; i >= 0; -- i)
		printf("%d", data[i]);
	printf("\n");
}
int main()
{
	//freopen("f://data.in","r",stdin);
	int T;
	scanf("%d", &T);
	BigNumber ans;
	while(T--)
	{
		ans = "0";
		char s[nMax];
		while(scanf("%s", s) != EOF)
		{
			if(s[0] == '0' && s[1] == 0)
				break;
			ans = ans + BigNumber(s);
		}
		ans.print();
		if(T)
			printf("\n");
	}
	return 0;
}

你可能感兴趣的:(HDU 1047 Integer Inquiry)