1019. Digital Black Hole

Given any 4-digit positive integer whose digits are not exactly the same, if we first sort the 4 numbers non-increasingly, then non-decreasingly, and then subtract the 2nd number from the 1st number, we will get a new number. Keep doing this over and over again, and we'll soon stop at 6174, known as the "digital black hole", the magic number also known as the Kaprekar constant.
For example, if we start with 6767, we will get

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

Now, given any 4-digit positive integer, write a program to demonstrate the process of reaching a black hole.
Input format:
Input gives a positive integer N in the interval (0, 10000).
Output format:
If the 4 digits of N are all equal, output "N - N = 0000" in one line; otherwise, output each step of the calculation in one line until 6174 appears as a difference, see the example for the output format. Note that each number is output in 4-digit format.

Input Sample 1:
6767
Output Sample 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

Input Sample 2:
2222
Output Sample 2:
2222 - 2222 = 0000

Note: After writing, I found that the code is very complicated, mainly because the sorting is very troublesome, it takes up a long period, and the main function part is also a little troublesome and needs to be optimized.

#include<stdio.h>
int main()
{
    int a[4];
    int i, p, q, N, flag;
    int num1, num2, num3;
    scanf("%d", &N);
    q = N;
    for (i=0; i<4; i++){
        a[i] = q%10;
        q /= 10;
    }
    void max(int a[], int n);
    void min(int a[], int n);
    if (a[0]==a[1] && a[1]==a[2]&& a[2]==a[3]) flag = 0;
    else flag = 1;

    if (flag==0)printf("%d - %d = 0000", N, N);
    else {
        num3 = 0;
        while (num3!=6174){
            max(a, 4);
            num1 = a[3]*1000+a[2]*100+a[1]*10+a[0];
            min(a, 4);
            num2 = a[3]*1000+a[2]*100+a[1]*10+a[0];
            num3 = num1-num2;
            printf("%04d - %04d = %04d", num1, num2, num3);
            p = num3;
            for (i=0; i<4; i++){
                a[i] = p%10;
                p /= 10;
            }
            printf("\n");
        }
    }
    return 0;
}
void max(int a[], int n){
    int i, j, k, t;
    int max;
    for (i=0; i<n-1; i++)
        for (j=0; j<n-i-1; j++)
        if (a[j]>a[j+1]){
            t = a[j];
            a[j] = a[j+1];
            a[j+1] = t;
        }
}
void min(int a[], int n){
    int i, j, k, t;
    int max;
    for (i=0; i<n-1; i++)
        for (j=0; j<n-i-1; j++)
        if (a[j]<a[j+1]){
            t = a[j];
            a[j] = a[j+1];
            a[j+1] = t;
        }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521966&siteId=291194637