欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PAT(A)1069 The Black Hole of Numbers (20分)

程序员文章站 2022-07-15 23:12:44
...

PAT(A)1069 The Black Hole of Numbers (20分)

Sample Input

6767

Sample Output

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

思路:
输入一个四位数,然后依次用最大的排序方式减最小的输出方式,如果结果时6174或者0000则输出。
我直接字符串输入,然后用高精度加法的方式去写,每次重排并赋值一下。
代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

bool cmp1(int a, int b)
{
    return a > b;
}

bool cmp2(int a, int b)
{
    return a < b;
}

int x[4];
int a[4], b[4], aa[4], bb[4];
int r[4];

int main()
{
    char n[4];

    scanf("%s", &n);

    for (int i = 4 - strlen(n); i <= 3; ++i)
        x[i] = n[i - 4 + strlen(n)] - '0';

    while (1)
    {
        sort(x, x + 4, cmp1);
        for (int i = 0; i <= 3; ++i)
            a[i] = x[i], aa[i] = x[i];


        sort(x, x + 4, cmp2);
        for (int i = 0; i <= 3; ++i)
            b[i] = x[i];

        for (int i = 3; i >= 0; --i)
        {
            if (a[i] - b[i] < 0)
            {
                a[i - 1]--;
                r[i] = a[i] - b[i] + 10;
            }
            else
                r[i] = a[i] - b[i];
        }

        for (int i = 0; i <= 3; ++i)
            printf("%d", aa[i]);
        printf(" - ");
        for (int i = 0; i <= 3; ++i)
            printf("%d", b[i]);
        printf(" = ");
        for (int i = 0; i <= 3; ++i)
            printf("%d", r[i]);
        if (r[0] == 6 && r[1] == 1 && r[2] == 7 && r[3] == 4)
            break;
        else if (r[0] == 0 && r[1] == 0 && r[2] == 0 && r[3] == 0)
            break;
        else
        {
            for (int i = 0; i <= 3; ++i)
                x[i] = r[i];
            printf("\n");
        }
    }
    // getchar(); getchar();

    return 0;
}