1. 程式人生 > 其它 >[PAT A1069 數字黑洞]

[PAT A1069 數字黑洞]

技術標籤:演算法筆記c++學習

[PAT A1069 數字黑洞]

Description:

For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number6174

-- theblack holeof 4-digit numbers. This number is named Kaprekar Constant.

For example, start from6767, we'll get:

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

Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

Input Specification:

Each input file contains one test case which gives a positive integerNin the range(0,10​4​​).

Output Specification:

If all the 4 digits ofNare the same, print in one line the equationN - N = 0000. Else print each step of calculation in a line until6174comes out as the difference. All the numbers must be printed as 4-digit numbers.

Sample Input 1:

6767

Sample Output 1:

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

Sample Input 2:

2222

Sample Output 2:

2222 - 2222 = 0000

CODE

#include <cstdio>
#include <algorithm>
using namespace std;

const int N=4;

int buffer2num(int *buffer,int len){
    int num=0;
    for(int i=0;i<len;i++){
        num=num*10+buffer[i];
    }
    return num;
}

void num2buffer(int *buffer,int len,int num){
    for(int i=len-1;i>=0;i--){
        buffer[i]=num%10;
        num/=10;
    }
}

void print_buffer(int *buffer,int len){
    for(int i=0;i<len;i++)
        printf("%d",buffer[i]);
}

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

int main(){
    int buffer[N]={0};
    int num=0;
    scanf("%d",&num);
    num2buffer(buffer,N,num);
    int res=0;
    while(res!=6174){
        sort(buffer,buffer+N,cmp);
        int a=buffer2num(buffer,N);

        print_buffer(buffer,N);

        printf(" - ");

        sort(buffer,buffer+N);
        int b=buffer2num(buffer,N);
        print_buffer(buffer,N);

        printf(" = ");

        res=a-b;

        num2buffer(buffer,N,res);
        print_buffer(buffer,N);

        printf("\n");
        
        if(res==0)break;
    }
    return 0;
}

注意:

1)類似進位制轉化,轉化程式碼要熟悉

2)傻逼了,列印的時候可以用格式化列印:printf("%04d - %04d = %04d\n",a,b,res);