1. 程式人生 > >大數A+B問題

大數A+B問題

原理

        大數運算的原理其實就是模擬人工計算(註記:再考慮是否有其他演算法。註記日期:2017.3.19),人工加法計算步驟如下:

    1.將兩個運算元(operand)位數對齊。

    2.從最低位開始,計算兩個運算元每位的總和再加上進位數(第一位數為0)的結果,保留其個位數。

    3.若上述的結果大於10,進位數置為1,否則為0。(每位數相加的結果不會超過 9 + 9 = 18 , 因此進位數只有1和0)

    4.重複上述步驟2、3,直到計算完兩個運算元其中那個位數小的最高位。

我們來看一道例題:

A+B Problem II

時間限制:3000 ms  |  記憶體限制:65535
 KB 難度:3
描述

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

A,B must be positive.

輸入
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.
輸出
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.
樣例輸入
2
1 2
112233445566778899 998877665544332211
樣例輸出
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
注意:此題有一個細節問題就是高位不能為0,舉個例子012+011不能等於033,而結果為33
現在我們來看一下程式碼的實現:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAX 1010
using namespace std;
char str1[MAX],str2[MAX];
int a[MAX],b[MAX],c[MAX]; 
int main()
{
	int t;
	int kase=0;
	cin>>t;
	while(t--)
	{
		memset(a,0,sizeof(a));//對陣列初始化 
		memset(b,0,sizeof(b));
		memset(c,0,sizeof(c));
		cin>>str1>>str2; 
		printf("Case %d:\n",++kase);
		printf("%s + %s = ",str1,str2);
		int len1=strlen(str1);
		int len2=strlen(str2);
		for(int i=len1-1,j=0;i>=0;i--)
		{
			a[j++]=str1[i]-'0';
		}
		for(int i=len2-1,j=0;i>=0;i--)
		{
			b[j++]=str2[i]-'0';
		}
		for(int i=0;i<MAX;i++)
		{
			c[i]+=a[i]+b[i];
			if(c[i]>=10)
			{
				c[i]=c[i]%10;//滿十進一 
				c[i+1]++;
			}
		}
		int j; 
		for(j=MAX-1;c[j]==0;j--);//避免高位等於0 
		if(j<0)
		cout<<0;
		else
		{
			for(;j>=0;j--)
			cout<<c[j];
		}
		cout<<endl; 
	}
return 0;
}