天天看點

hdu1002(高精度加法運算)

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 434867 Accepted Submission(s): 84639

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

這是一個高精度加法運算,已有的資料類型資料範圍不夠。隻能另想它法。代碼參考了老師另一個程式的代碼,讓代碼更加簡潔易懂。

程式思路:

1、用字元數組儲存大數,此時使用scanf很友善。

2、注意讀入的大整數高位在數組的低位。

3、另外一個結果數組ans中首先将一個數組的值拷貝過來,ans數組低位放數的低位,以便進位産生更高的位。

4、将另一個數組的數加到ans中,注意進位(carry)。

5、這兩個數組的長度可能不一緻。是以使用while(carry > 0){}(代碼37行處),可以使高位産生的連續進位得到處理。

6、考慮到while(carry > 0){}中j++會産生多餘的位(為0)同時考慮到00…00 + 00…00 的情況,要去除前導0。(代碼46行處)

#include<iostream>
	#include<stdio.h>
	#include<string.h>
	
	using namespace std;
	
	const int N = 1000;
	const int BASE = 10;
	
	char a[N+1],b[N+1],ans[N+1];
	
	
	int main(){
		int t,i,j,k,len,anslen,carry;
		cin>>t;
		for(k = 1;k <= t;k++){
			scanf("%s%s",a,b);
			
			memset(ans,0,sizeof(ans));
			
			anslen = len = strlen(a);
			
			for(i = len - 1,j =0;i >= 0;i--)
				ans[j++] = a[i] - '0';
				
			len = strlen(b);
			if(len > anslen)
				anslen = len;
			
			carry = 0;
			for(i = len-1,j=0;i >= 0;i--,j++){
				ans[j] += b[i] - '0' + carry;
				carry = ans[j] / BASE;
				ans[j] %= BASE;
			}
			
			while(carry > 0){
				ans[j] += carry;
				carry = ans[j] / BASE;
				ans[j++] %= BASE;
			}
			
			if(j > anslen)
				anslen = j;
			//去除前導0
			for(i = anslen -1;i >= 0;i--)
				if(ans[i])
					break;
			
			if(i < 0)
				i = 0;
			//輸出
			cout<<"Case "<<k<<":"<<endl;
			for(j = 0;j < strlen(a);j++)
				cout<<a[j] - '0';
			cout<<" + ";
			
			for(j = 0;j < strlen(b);j++)
				cout<<b[j] - '0';
			cout<<" = ";
			for(;i>=0;i--)
				cout<<(int)ans[i];
			cout<<endl;	
			if(k != t) cout<<endl;
		}
		
		
		return 0;
	}
           

此時就可以AC了。

繼續閱讀