ACM——hdu1002(高精度加法)
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.
(第一行輸入一個數字T(1 <= T <= 20)代表輸入的資料組數,其後輸入T行,每行包含2個欲求和的數字A和B,由於這兩個數非常大,這意味著你不能用32位整數來處理它們,同時,你可以假定每個數字不超過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.
(注意輸出的格式,對於每一種案例,你需要輸出兩行,第一行為“Case#:”,指示這是第幾個測試樣例,第二行為一個公式”A + B = Sum”,Sum表示A加B的結果。注意在等式中有一些空格,在兩個樣例間輸出一空白行。)
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
解題思路:
- 首先用2個字串儲存要輸入的兩個加數A、B;
- 去掉字串中多餘的0,比如0001改為1;
- 將字串轉換為整型陣列並倒序儲存(ASCII中,‘1’-‘0’=1);
- 對A、B陣列每一位進行加法運算,並存儲在另一個數組中;
- 按要求輸出結果;
- 將各個資料清0。
Submission
#include <stdio.h>
#include <string.h>
int main() {
int m,n,i,j,k;
char a[1000]={0};
char b[1000]={0};
int a1[1000]={0};
int b1[1000]={0};
int c[1001]={0};
int la,lb,la1,lb1,max;
scanf("%d",&n);
for(m=1;m<=n;m++)
{
scanf("%s %s",&a,&b);
la=strlen(a);
lb=strlen(b);
for(i=0;i<la;i++){ //去掉A中的前導零
if(a[i]!='0' && a[i]!=NULL){
la1=i;
break;
}
else if(a[i]=='0' && i==la-1){
la1=0;
la=1;
}
}
/*從字串的第一個字元開始遍歷,遇到'0'跳過,直到遇到字串中第一個不為'0'的字元,若整個字串全為'0',則遍歷完整個字串。比如字串'00999',遍歷到第一個字元'0',la1為0,到第二字元'0',la1為0,第三個字元不為'0',la1為2,那麼之後字串是從第三位開始倒序儲存的,這樣就清除了前導的'0'。*/
for(i=0;i<lb;i++){ //去掉B中的前導零
if(b[i]!='0'&&b[i]!=NULL){
lb1=i;
break;
}
else if(a[i]=='0'&&i==la-1){
lb1=0;
lb=1;
}
}
for(j=la-1,k=0;j>=la1;j--,k++){//倒置字串,並轉換為整型陣列
a1[k]=a[j]-'0';//ASCII碼中,字元‘0’和數字0相差
}
for(j=lb-1,k=0;j>=lb1;j--,k++){
b1[k]=b[j]-'0';
}
if(la>=lb) max=la;
else max=lb;
for(i=0;i<max;i++){//進行加法運算
if(a1[i]+b1[i]+c[i]>=10){
c[i]=a1[i]+b1[i]+c[i]-10;
c[i+1]=c[i+1]+1;
}
//當有進位時,此位減10,高一位加1;無進位時,此位A、B對應的加數和進位相加。
else{
c[i]=a1[i]+b1[i]+c[i];
}
}
printf("Case %d:\n",m);//輸出結果
for(j=la1;j<la;j++){
printf("%c",a[j]);
}
printf(" + ");
for(j=lb1;j<lb;j++){
printf("%c",b[j]);
}
printf(" = ");
if(c[max]==0) max=max-1;
for(j=max;j>=0;j--){
printf("%d",c[j]);
}
if(m!=n){
printf("\n\n");
}
else{
printf("\n");
}
for(j=0;j<=max;j++){ //將陣列清0
a1[j]=0;
b1[j]=0;
c[j]=0;
}
}
return 0;
}
寫這道題比較糟心的地方有經過一次樣例輸出後忘記將資料清0,導致後面的樣例全都計算錯誤,不過除錯之後就解決啦!