码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1002--A + B Problem II

时间:2014-06-08 04:56:06      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:hduoj sum

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 203220    Accepted Submission(s): 39047


Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

Sample Input
2 1 2 112233445566778899 998877665544332211
 

Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
 

Author
Ignatius.L
 
解析:其实就是实现加法运算,数组模拟大数加法,输入的时候采用字符串输入,一定要考虑到如果两数的长度不同的情况,还有加法进位的处理,最后还有输出的+=左右都有空格,最后那组数据不再输出空行,需要考虑的情况还真多,wa了几次哈!
贴一下自己的代码
#include<iostream>
#include <string>
#include<algorithm>
using std::endl;
using std::cin;
using std::cout;
using std::string;
int main()
{
#ifdef LOCAL
	freopen("input.txt" , "r" , stdin);
	freopen("output.txt" , "w" , stdout);
#endif
	int T;
	cin >> T;
	string a , b , sum;
	for(int cases = 1; cases<=T; ++cases)
	{
		sum.clear();
		cin >> a >> b;
		cout << "Case " << cases << ":" << endl;
		cout << a <<" + "<<b << " = ";
		int c = 0 ;
		reverse(a.begin() , a.end());
		reverse(b.begin() , b.end());
		int alength = a.length();
		int blength = b.length();
		int length = alength;
		//使两个字符串的长度相等,补齐零
		if(alength < blength)
		{
			for(int i=alength; i<blength; ++i)
			{
				a += '0';
			}
			length = blength;
		}
		if(blength < alength)
		{
			for(int i=blength; i<alength; ++i)
			{
				b +='0';
			}
			length = alength;
		}
		//进行加法计算,c为进位
		for(int i=0; i<length; ++i)
		{
			int temp = (a[i] - '0') + (b[i] - '0') +c;
			c = temp/10;
			sum += (temp%10 + '0');
		}
		//最高位的进位如果不为0的话则进位
		if(c!=0)
		{
			sum += (c +'0');
		}
		//结果转置
		reverse(sum.begin() , sum.end());
		cout << sum << endl;
		//控制最后的那组数据不再输出空行
		if(cases != T)
		{
			cout << endl;
		}
	}
}


HDU1002--A + B Problem II,布布扣,bubuko.com

HDU1002--A + B Problem II

标签:hduoj sum

原文地址:http://blog.csdn.net/computer_liuyun/article/details/29221715

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!