现在的位置: 首页 > 综合 > 正文

HDOJ 1002 A + B Problem II

2014年09月05日 ⁄ 综合 ⁄ 共 869字 ⁄ 字号 评论关闭

        更新:2014-01-30    下午

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        来源:http://acm.hdu.edu.cn/showproblem.php?pid=1002

        概述:大数相加问题——两个1000位以内的正整数相加

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        “显示”解释:用cout输出string类型,所得即所见。

        MyAdd()中:输入参数s1和s2是用字符串“显式”表示的大非负整数。通过计算,将结果存储在s1。

#include <iostream>
#include <string>
using namespace std;

string MyAdd(string s1, string s2)
{
	// 确保s1长度上不小于s2
	if (s2.size() > s1.size()) swap(s1, s2);

	// 计算中都是把s2加入s1
	string::iterator p1 = s1.end(), p2 = s2.end();
	while (p2 != s2.begin())
	{
		*p1 += *p2 - '0';
		if (*p1 > '9') *p1 -= 10, *(p1-1) += 1;
		p1--, p2--;
	}

	*p1 += *p2 - '0';
	while (*p1 > '9')
	{
		*p1 -= 10;
		if (p1 == s1.begin())
		{
			s1 = '1' + s1;
			break;
		}
		
		p1--;
		*p1 += 1;
	}
	return s1;
}

int main()
{
    int T;
    cin >> T;
    for (int t = 1; t <= T; t++)
    {
        string s1, s2;
		cin >> s1 >> s2;
		cout << "Case " << t << ":" << endl
			 << s1 << " + " << s2 << " = "
			 << MyAdd(s1, s2) << endl;
		if (t != T) cout << endl;
    }
    return 0;
}

抱歉!评论已关闭.