码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1069. The Black Hole of Numbers

时间:2015-02-19 12:54:32      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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
思路:熟悉运用sscanf ,ssprintf ,另外还有%04d
技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 bool cmphigh(char A,char B)
 6 {
 7     return A>B;
 8 }
 9 bool cmplow(char A,char B)
10 {
11     return A<B;
12 }
13 
14 int main(int argc, char *argv[])
15 {
16     int n;
17     scanf("%d",&n);
18     char high[5],low[5];
19     int ans=n;
20     bool  first=true;
21     while(ans!=6174||first)
22     {
23         first=false;
24         sprintf(high,"%04d",ans);
25         sprintf(low,"%04d",ans);
26         int big,small;
27         sort(high,high+4,cmphigh);
28         sscanf(high,"%d",&big);
29         sort(low,low+4,cmplow);
30         sscanf(low,"%d",&small);
31         ans=big-small;
32         printf("%04d - %04d = %04d\n",big,small,ans);
33         if(ans==0)
34           break;
35     }
36     
37     return 0;
38 }
View Code

 

PAT1069. The Black Hole of Numbers

标签:

原文地址:http://www.cnblogs.com/GoFly/p/4296062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!