1019 digital black hole (C language)

Given any one of the digits not identical four positive integer, if we first four digits ordered by nonincreasing, then a non-descending order, and then the first number minus the second number, will get a new digital. Has been repeated so doing, we will soon be parked in the "digital black hole," said the 6174, the magic number is also called Kaprekar constant.

For example, from the 6767start, will be

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

Now given any four positive integers, write a program demonstrates the process of reaching the black hole.

Input formats:

A given input (0,10 4 positive integer) of section N.

Output formats:

If N is equal to 4-bit digital full, then the output line N - N = 0000; otherwise, the output of each step will be calculated in a row, until 6174a difference is present, see the sample output format. Note that each of the 4 bits output in digital format.

Sample Input 1:

6767

Output Sample 1:

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

Sample Input 2:

2222

Output Sample 2:

2222 - 2222 = 0000

Herein may be utilized to complete the corresponding bubble sort operation.

#include<stdio.h>
int a[10];
void toArry(int n){            //将数转化为数组存储
    int i;
    for(i=3;i>=0;i--){
        a[i]=n%10;
        n=n/10;
    }
}
int toNumber(int a[]){          //将数组转化为数
    int i;
    int sum=0;
    for(i=0;i<4;i++){
        sum= sum*10+a[i];
    }
    return sum;
}
void Maxsort(int a[]){          //按从大到小排序
    int i,j;
    for(j=0;j<4;j++){
        for(i=j;i<3;i++){
            if(a[j]<a[i+1]){
                int temp;
                temp=a[j];
                a[j]=a[i+1];
                a[i+1]=temp;
            }
        }
    } 
}
void Mminsort(int a[]){         //按从小到大排序
    int i,j;
    for(j=0;j<3;j++){
        for(i=j;i<3;i++){
            if(a[j]>a[i+1]){
                int temp;
                temp=a[j];
                a[j]=a[i+1];
                a[i+1]=temp;
            }
        }
    } 
}
int main()
{
    int n;
    scanf("%d",&n);
    while(1){
        toArry(n);
        Maxsort(a);
        int max=toNumber(a);
        Mminsort(a);
        int min=toNumber(a);
        n=max-min;
        printf("%04d - %04d = %04d\n",max,min,n);  //注意输出的格式,需要是4位不够用0填补
        if(n==0||n==6174){
            break;
        }
    }
    return 0;
}
Released five original articles · won praise 0 · Views 56

Guess you like

Origin blog.csdn.net/Czrobe/article/details/104927189