【PTA A1069】1069 The Black Hole of Numbers (20)(20 分)

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 number 6174 -- the "black hole" of 4-digit numbers. This number is named Kaprekar Constant.

For example, start from 6767, 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 integer N in the range (0, 10000).

Output Specification:

If all the 4 digits of N are the same, print in one line the equation "N

N = 0000". Else print each step of calculation in a line until 6174 comes 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

分析:

簡(jiǎn)單題
主要考的是閱讀理解(笑),輸入一個(gè)四位數(shù)字,讓它的數(shù)字從大到小排列-從小到大排,知道得到一個(gè)神奇的數(shù)6174為止
主要是兩個(gè)函數(shù)to_array和to_num,排序用sort就行了。

code:

#include<cstdio> 
#include<algorithm>
using namespace std;
void to_array(int n,int a[]){
    for(int i=0;i<4;i++){
        a[i]=n%10;
        n=n/10;
    }
}

int to_number(int a[]){
    int sum=0;
    for(int i=0;i<4;i++){
        sum=sum*10+a[i];
    }
    return sum;
}

bool cmp(int a,int b){
    return a>b;
}
int main(){
    int n=0;
    int max,min=0;
    int a[10];
    scanf("%d",&n);
    while(1){
        to_array(n,a);
        sort(a,a+4);
        min=to_number(a);
        sort(a,a+4,cmp);
        max=to_number(a);
        n=max-min;
        printf("%04d - %04d = %04d\n",max,min,n);
        if(n==6174||n==0)
            break;
    }
    system("pause");
    return 0;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評(píng)論 0 10
  • 01 天氣由溽熱到?jīng)鏊?,心情也為之大好?從6月23日到現(xiàn)在,已經(jīng)是一個(gè)多月的時(shí)間,這段時(shí)間里我讓自己徹底地放松了...
    梅洛的聽雨軒閱讀 303評(píng)論 2 1
  • 今天是母親節(jié),在這里首先祝天底下所有媽媽們節(jié)日快樂,你們辛苦了!今晚去做了頭發(fā),一下午也沒見兩包,回到家就快十點(diǎn)了...
    輕描淡寫的小情緒晴閱讀 157評(píng)論 0 0
  • 2014年,10月1日,由許鞍華導(dǎo)演,湯唯主演的《黃金時(shí)代》在全國(guó)公映,這是關(guān)于蕭紅一生的記錄。 屏幕里湯唯飾演的...
    小雨rainy_愛我小可可閱讀 478評(píng)論 0 0
  • 幾步畫個(gè)美男子
    三青w閱讀 528評(píng)論 1 3

友情鏈接更多精彩內(nèi)容