HDU 1002 A + B Problem II

题目链接:A + B Problem II

解题思路:大数加法,主要是对字符串的操作,很考验基本功。

#include<string.h>
#include<stdio.h>
#define MAX 1010

char a1[MAX], a2[MAX];
int ans[MAX];

void add(){
    int index1 = strlen(a1) - 1, index2 = strlen(a2) - 1;
    int b1, b2, tem, i;
    b1 = b2 = tem = 0;
    i = MAX - 1; 
    while(index1 >= 0 || index2 >= 0){
        b1 = index1 < 0 ? 0 : a1[index1] - '0';
        b2 = index2 < 0 ? 0 : a2[index2] - '0';
        ans[i] = (b1 + b2 + tem) % 10;
        tem = (b1 + b2 + tem) / 10;
        index1--;
        index2--;
        i--;
    }
    ans[i] = tem;
}

int main(){
    int i, j, t, k = 1;
    scanf("%d", &t);
    while(t--){
        if(k != 1){
            printf("\n");
        } 
        memset(ans, 0, sizeof(ans)); 
        scanf("%s %s", &a1, &a2);
        add();
        printf("Case %d:\n", k++);
        printf("%s + %s = ", a1, a2);
        for(i = 0; i < MAX; i++){
            if(ans[i]){
                break;
            }
        }
        for(;i < MAX; i++){
            printf("%d", ans[i]);
        }
        printf("\n");
    }
    return 0;    
}


 

 

你可能感兴趣的:(HDU 1002 A + B Problem II)