hdu 1002 A+B 2大数相加

hdu 1002 A+B 2大数相加

1.注意输入直接用字符串输入;
2.注意看清题目;
3.特别小心自增自减的使用,避免使用到不合理的值;
4.利用测试不断优化程序。

#include<iostream>
using namespace std;


int main()
{
	int n;
	char m[1005], p[1005];
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> m >> p;
		cout << "Case " << i+1<<":" << endl;
		cout << m << " + " << p << " = ";
		//cout << endl << m << endl << p<<endl;
		char c[1005] = { '0' }; 
		for (int pp = 0; pp < 1005; pp++)
		{
			c[pp] = '0';
		}
		//cout << endl << c[20] << endl;
		int m_len = strlen(m); int p_len = strlen(p);
		int min = m_len < p_len ? m_len : p_len; 
		int max = m_len > p_len ? m_len : p_len;

		c[max + 1] = '\0';
		for (int j = 0; j < min; j++)
		{
			char oo = c[max];
			c[max] = (oo - '0' + m[--m_len] + p[--p_len] - '0' - '0') % 10 + '0';
			if ((oo-'0'+m[m_len] + p[p_len] - '0' - '0') / 10 != 0)
			{
				c[max-1]+=1;
			}
			max--;
		}
		if (m_len != 0)
		{
			while (m_len != 0)
			{
				char oo = c[max];
				//cout << endl << oo<<endl;
				c[max] = (c[max] - '0' + m[m_len - 1] - '0') % 10 + '0';
				//cout << endl << c[max]<<endl;
				if ((oo - '0' + m[m_len - 1] - '0') / 10 != 0)
				{
					c[max-1]+=1;
				}
				--max;
				m_len--;
			}
		}
		if (p_len != 0)
		{
			while (p_len != 0)
			{
				char oo = c[max];
				c[max] = (c[max] - '0' + p[p_len - 1] - '0') % 10 + '0';
				if ((oo - '0' + p[p_len - 1] - '0') / 10 != 0)
				{
					c[max-1]+=1;
				}
				--max;
				p_len--;
			}
		
		}
		if (c[0] != '0')
		{
			cout << "1";
		}
		for (int u = 1; u < strlen(c); u++)
		{
			cout << c[u];
		}
		cout << endl;
		if (i != n - 1)
			cout << endl;
	}

	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值