1069. The Black Hole of Numbers

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 = 10899810 – 0189 = 96219621 – 1269 = 83528532 – 2358 = 61747641 – 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.

这题跟B19是一样的

#include <stdio.h>#include <stdlib.h>#include <algorithm>using namespace std;int Sort1(int a1,int a2,int a3,int a4);int Sort2(int a1,int a2,int a3,int a4);int main (){int a1=0,a2=0,a3=0,a4=0,i=0;int num;scanf("%d",&num);a1=num/1000;a2=(num/100)%10;a3=(num%100)/10;a4=num%10;if(a1==a2 && a2==a3 && a3==a4){printf("%d%d%d%d – %d%d%d%d = 0000\n",a1,a1,a1,a1,a1,a1,a1,a1);return 0;}int result=0,first=0,second=0;while(1){first=Sort2(a1,a2,a3,a4);second=Sort1(a1,a2,a3,a4);result=first-second;a1=result/1000;a2=(result/100)%10;a3=(result%100)/10;a4=result%10;printf("%04d – %04d = %04d\n",first,second,result);if(result==6174||result==0) break;}system("pause");return 0;}int Sort1(int a1,int a2,int a3,int a4){int a[4]={a1,a2,a3,a4};sort(a,a+4);return (a[0]*1000+a[1]*100+a[2]*10+a[3]);}bool cmp(int a,int b){return a>b;}int Sort2(int a1,int a2,int a3,int a4){int a[4]={a1,a2,a3,a4};sort(a,a+4,cmp);return (a[0]*1000+a[1]*100+a[2]*10+a[3]);}

,就是对虚怀若谷谦虚谨慎八个字真正理解的人,

1069. The Black Hole of Numbers

相关文章:

你感兴趣的文章:

标签云: