Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 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 = 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

解答

#include <cstdio>
#include <algorithm>
#include <functional>
using namespace std;

int main()
{
	int n; scanf("%d", &n);
	do //至少打印一次结果,即使是6174本身
	{
		char a1[10]; sprintf(a1,"%04d", n);
		sort(a1, a1 + 4, greater<int>());
		int n1 = 0;
		for (int i = 0; i < 4; i++) n1 = n1 * 10 + a1[i] - '0';
		
		char a2[10]; sprintf(a2,"%04d", n);
		sort(a2, a2 + 4);
		int n2 = 0;
		for (int i = 0; i < 4; i++) n2 = n2 * 10 + a2[i] - '0';

		printf("%s - %s = %04d\n", a1, a2, n = n1 - n2);
	} while (n && n != 6174);
	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论