HDU1002--A + B Problem II

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;
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章