1. 程式人生 > >hdu1002(高精度加法運算)

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了。