题目要求:
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
思路分析:
本题的主要问题充分考虑出现的情况,然而,由于C++总体库的存在,本体难度较低。
本题主要地方有:(1)、四位数转数组 ; (2)、数组转数字,(3)、数组的排序
代码展示:
#include <algorithm>
#include <cstdio>
using namespace std;
bool cmpND(int a,int b){
return a>=b;
}
bool cmpNI(int a,int b){
return a<=b;
}
int num1[4]={0}; //存放非递增数据
int num2[4]={0}; //存放非递减数据
int result[4]={0};
//存储进行运算的四位数
void store(int num){
for(int i=0;i<4;i++){
num1[3-i] = num%10;
num2[3-i] = num%10;
num /= 10;
}
sort(num1,num1+4,cmpND);
sort(num2,num2+4,cmpNI);
}
//存储每次运算的结果
void storeRes(int res){
for(int i=0;i<4;i++){
result[3-i] = res%10;
res /= 10;
}
}
//把数组中的数转化为四位数字返回
int changToNum(int A[]){
int sum=0;
for(int i=0;i<4;i++){
sum *= 10;
sum += A[i];
}
return sum;
}
//格式化输出结果
void show(){
for(int i=0;i<4;i++){
printf("%d",num1[i]);
}
printf(" - ");
for(int i=0;i<4;i++){
printf("%d",num2[i]);
}
printf(" = ");
for(int i=0;i<4;i++){
printf("%d",result[i]);
}
printf("\n");
}
int main(){
int num;
scanf("%d",&num);
int res = num;
do{
store(res);
res = changToNum(num1)-changToNum(num2);
storeRes(res);
show();
}while( res !=0 && res!= 6174);
return 0;
}
注意:
本题要注意的地方应该是在#include<algorithm>下,需要使用using namespace std了;
其他就是细心