A1069 The Black Hole of Numbers (20 point(s))

数字转数组,数组转数字

1. 原文

原题

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:

1
2
3
4
5
6
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,10^4).

output Specification:

f 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:

1
6767

Sample output 1:

1
2
3
4
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

Sample Input 2:

1
2222

Sample output 2:

1
2222 -2222 = 0000

2. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<cstdio>
#include<algorithm>
using namespace std;
bool cmp(int x,int y){
return x>y;
}
void toarray(int num[],int x)
{
for (int i = 0; i < 4; ++i)
{
num[i]=x%10;
x=x/10;
}
}
int tonum(int num[]){
int x=0;
for (int i = 0; i < 4; ++i)
{
x=x*10+num[i];
}
return x;
}
int num[10010]={};
int main()
{
int n;
scanf("%d",&n);
while(true){

toarray(num,n);

sort(num,num+4,cmp);
int a=tonum(num);

sort(num,num+4);
int b=tonum(num);

printf("%04d - %04d = %04d\n",a,b,a-b);
if (a-b==0||a-b==6174)
{
break;
}
n=a-b;

}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1069/
  • 发布时间: 2019-09-03 12:32
  • 更新时间: 2021-10-29 14:03
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!