A-B Problem Plus[Medium]

题目描述

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

解答要求
时间限制:1000ms, 内存限制:100MB
输入
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 = ?", ? means the result of A - B.Note there are some spaces int the equation. Output a blank line between two test cases.

样例
输入样例 1 复制

3
9 8
12 8
123456789 987654321
输出样例 1

Case 1:
9 - 8 = 1

Case 2:
12 - 8 = 4

Case 3:
123456789 - 987654321 = -864197532

与大数相加的差异

1.减法的借位和两个数之间大小的问题
2.按字符串来考虑后,需要处理掉输出前面的‘0’,这也是计算reslen的目的

代码

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

#define MAX_NUM 500
int BigNumberSub(char *a, char *b, int *calcResult)
{
int lenA = strlen(a);
int lenB = strlen(b);
int carry = 0;
int resLen = 0;
while (lenA > 0 || lenB > 0 || carry > 0) {
    int chA = lenA > 0 ? a[lenA - 1] - '0' : 0;
    int chB = lenB > 0 ? b[lenB - 1] - '0' : 0;
    //int temp = chA + chB + carry;
    int temp;
    chA=chA-carry;
    if(chA<chB){
        temp=chA+10-chB;
        carry=1;
    }
    else{ 
        temp=chA-chB;
        carry=0;
    }
    //carry = temp / 10;
    calcResult[resLen++] = temp;
    lenA--;
    lenB--;
    }
return resLen;
}

int main()
{
int t;
scanf_s("%d", &t);
    
int count = 0;
while (t--) {
    char a[MAX_NUM];
    char b[MAX_NUM];
    scanf_s("%s%s", a, sizeof(a), b, sizeof(b));
    
    int calcResult[MAX_NUM];
    int reslen=0;
    int sym=1;
    if(strlen(a)<strlen(b)){
        reslen = BigNumberSub(b, a, calcResult);
        sym=0;
    }
    else if(strlen(a)==strlen(b)){
        int flag=strcmp(a,b);
        if(flag<0){
            reslen = BigNumberSub(b, a, calcResult);
            sym=0;
        }
        else
            reslen=BigNumberSub(a, b, calcResult); 
    }
    else
        reslen=BigNumberSub(a, b, calcResult);
    
    count++;
    printf("Case %d:\n", count);
    printf("%s - %s = ", a, b);
    int i=reslen-1;
	//去掉前面的0
    while (calcResult[i]==0) {
        i--;
    }
	//判断正负号
    if(sym==0){
        printf("-");
    }
    for (i; i >= 0; i--) {
    printf("%d", calcResult[i]);
    }
printf("\n\n");
}
return 0;
}
posted @ 2022-02-08 15:43  ly-828  阅读(105)  评论(0)    收藏  举报