题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805400954585088
1069 The Black Hole of Numbers (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,104).
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
题目大意:https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968,与乙级题目 ”数字黑洞一样“一样
解题思路:将过程模拟出来就是了。首先需要输入一个n,表示开始的数字,建立一个while(n)循环,里面是n这样n为0的时候就可以跳出循环,结束循环的条件n为0或者n==6174,不然需要一直循环下去,直到满足条件。建立一个数组a[]来存储n中每一位的数字,一共四位,再将a[]从大到小排序,然后将a[]中的四个数字恢复成一个四位的整数,这样就得出第一个数字,同理,从小到大排序,再恢复成四位的整数,得到第二个数字,第二个数字见去第一个数字赋值给n,将这三个数字按照格数输出即可,n不满足条件继续循环。注意:输出的数字需要时四位,不足四位需要从前面填0,补成四位。
代码如下:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool cmp(int a, int b) //从大到小排序
{
return a > b;
}
int to_int(int s[]) //将每位数字合并成一个四位的整数
{
int a = 0;
for (int i = 0; i < 4; i++)
{
a = a * 10 + s[i];
}
return a;
}
int main()
{
int n;
int a[5]; //用来存储每位数字
int max; //存储从大到小排序之后的整数
int min; //从小到大排序之后的整数
cin >> n;
while (n) //n为0的时候直接退出循环
{
for (int i = 0; i < 4; i++) //将一个四位整数拆开,每一位分别存储到数组中
{
a[i] = n % 10;
n /= 10;
}
sort(a, a + 4, cmp); //从大到小排序
max = to_int(a); //大数
sort(a, a + 4); //从小到大排序
min = to_int(a); //小数
n = max - min; //相减之后的数
printf("%04d - %04d = %04d\n", max, min, n);
if (n == 6174) //等于6174的时候退出
break;
}
return 0;
}