1. 程式人生 > >HDU 1002 A + B Problem II

HDU 1002 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): 439087 Accepted Submission(s): 85433 原題連結

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

題解:題目要求求A+B的值,但是會很大,所以需要用陣列存,說下我的思路,兩個字元數分別存兩串數,長的放在num1,短的放num2,翻轉後計算,一位一位加,用一個變數(k2)來表示上一位的進位,如果進位就為1,未進位就為0,num1[i] + num2[i]+k2 的值如果轉換成數值後大於等於10就進位,反之就不進位,依次計算就行了,需要注意的是中間num2的字元用完了,表示當前值的變數就從num1[i] + num2[i]+k2 變成num1[i]+k2。還有最後如果k2不為0的話那麼就表示前面還有一位沒有放進去需要單獨放個1在前面。下面是AC程式碼:

#include"iostream"
#include"algorithm"
#include"string"

using namespace std;

int main()
{
	int n,j=1;
	cin >> n;
	while(n--)
	{
		string num,num1,num2,num4,num5;//新數,數1,數2,數1備份,數2備份 
		cin >> num1 >> num2;
		num4 = num1,num5=num2;
		if(num1.length() < num2.length()) //長的放在num1 
			num1 = num5,num2 = num4;
		reverse(num1.begin(),num1.end());//翻轉字串 
		reverse(num2.begin(),num2.end());
		int i,k,k2=0;//下標,當前位的值,進位值 
		for(i=0;i<num1.length();i++)
		{
			if(i >= num2.length()) k = num1[i]-48 + k2;//num2用完就只用num1 
			else k = (num1[i]-48) + (num2[i]-48) + k2;
			if(k <= 9)
			{	
				num = (char)(k+48)+num;
				k2 = 0;
			}	
			else
			{
				num = (char)(k-10+48)+num;
				k2 = 1;
			}
		}
		if(k2) num = '1'+num;//如果最後還需要進位,則單獨在前面放個1 
		cout << "Case " << j << ":" << endl;
		cout << num4 << " + " << num5 << " = " << num << endl;
		j++;
		if(n-1 >= 0) cout << endl;//控制格式 
	}
	return 0;
}