A+B Problem Plus

 

 

//we have defined the necessary header files here for this problem.
//If additional header files are needed in your program, please import here.

#include <stdio.h>
#include <string.h>

#define LENGHT 1000

void sumPlus(char *a, char *b);

void reverse(char *a);

int main() {
    int times;
    scanf("%d", &times);
    char operator[2][LENGHT] = {{'0'},
                                {'0'}};
    for (int i = 0; i < times; ++i) {
        scanf("%s %s", operator[0], operator[1]);
        printf("Case %d:\n", i + 1);
        printf("%s + %s = ", operator[0], operator[1]);
        sumPlus(operator[0], operator[1]);
        if (i != times - 1) {
            printf("\n");
            printf("\n");
        }
    }
    return 0;
}

void sumPlus(char *a, char *b) {
    int res[LENGHT + 1] = {0};
    reverse(a);
    reverse(b);
    int flag_a = 0, flag_b = 0, carry = 0;  //进位
    for (int i = 0; i < LENGHT; ++i) {
        int x = 0, y = 0;
        if (a[i] == '\0')
            flag_a = 1;
        if (b[i] == '\0')
            flag_b = 1;
        if (!flag_a) {
            x = a[i] - '0';
        }
        if (!flag_b) {
            y = b[i] - '0';
        }
        int temp = x + y + carry; //字符类型转int类型
        res[i] = temp % 10;
        carry = temp / 10;
    }
    int i = LENGHT;
    while (res[i] == 0) {
        i--;
    }
    while (i >= 0) {
        printf("%d", res[i]);
        i--;
    }
}

void reverse(char *a) {
    int size = strlen(a);
    char temp[LENGHT + 1] = {'0'};
    for (int i = size - 1, j = 0; i >= 0; --i, ++j) {
        temp[j] = a[i];
    }
    memcpy(a, temp, size);
//    a[size] = '\0';
}

猜你喜欢

转载自www.cnblogs.com/ustc-anmin/p/11635901.html
今日推荐