PAT (Advanced Level) Practice 1069 The Black Hole of Numbers (20 分) 凌宸1642

PAT (Advanced Level) Practice 1069 The Black Hole of Numbers (20 分) 凌宸1642

题目描述:

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.

译:给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。

例如,我们从6767开始,将得到

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...

现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。


Input Specification (输入说明):

Each input file contains one test case which gives a positive integer N in the range (0,104).

译:输入给出一个 (0,104) 区间内的正整数 N 。


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.

译:如果 N 的 4 位数字全相等,则在一行内输出 N - N = 0000;否则将计算的每一步在一行内输出,直到 6174 作为差出现,输出格式见样例。注意每个数字按 4 位数格式输出。 .


Sample Input 1 (样例输入 1 ):

6767

Sample Output 1 (样例输出 1 ):

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

Sample Input 2 (样例输入 2 ):

2222

Sample Output 2 (样例输出 2 ):

2222 - 2222 = 0000

The Idea:

没有什么好说的,就是判断一下呗,依照题目意思就行转化就行。

The Codes:

#include<bits/stdc++.h>
using namespace std ;
int num[4] = {0} , n ;
int main(){
	while(scanf("%d" , &n) != EOF){
		memset(num , 0 , sizeof(num)) ; // 重置数组的每一位都是 0 
		int tem = n ;
		for(int i = 0 ;tem != 0 ;i ++ , tem /= 10) num[i] = tem % 10 ; // 得到4位数的每一位
		if((num[0] == num[1])&&(num[1] == num[2])&&(num[2] == num[3])) //判断是否4位数均相同
			printf("%04d - %04d = 0000\n" , n , n) ;
		else{
			int res = n;
			do{
				memset(num , 0 , sizeof(num)) ; // 重置数组的每一位都是 0 
				int t = res;
				for(int i = 0 ; t != 0 ; i ++ , t /= 10) num[i] = t % 10;
				sort(num , num + 4) ; // 将四位数从小到大排序
				int left = num[3] * 1000 + num[2] * 100 + num[1] * 10 + num[0] ;//大4位数
				int right = num[0] * 1000 + num[1] * 100 + num[2] * 10 + num[3] ;//小4位数
				res = left - right ; // 大减小的和
				printf("%04d - %04d = %04d\n" , left , right , res) ;
			}while(res != 6174) ;
		}
	}
	return 0;
}

posted @ 2021-04-11 00:49  凌宸1642  阅读(52)  评论(0编辑  收藏  举报