PAT 1069

题目 : The Black Hole of Numbers

分值 : 20
难度 : 简单题
思路 : 搞个数组存四个数字,然后升序排,降序排,减一下,递归知道到最终答案或者0
坑点 : 你用char[5]存,会超时,不知道为什么,改成int[4]就好了

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a ,int b )
{
return a>b ;
}
bool cmp2(int a ,int b)
{
return b > a ;
}
int main() {
int s[4] ;
int x = 0 ;
scanf("%d",&x);
int temp = 1 ;
while(temp != 0 && temp != 6174)
{
s[0] =x/1000 ; s[1] = (x%1000)/100 ;s[2] = (x%100)/10 ; s[3] = (x%10);
sort(s , s+4 ,cmp) ;
temp = s[0]*1000 + s[1]*100+s[2]*10 +s[3] ;
cout <<s[0]<<s[1]<<s[2]<<s[3]<<" - ";
sort(s , s+4 ,cmp2);
cout <<s[0]<<s[1]<<s[2]<<s[3]<<" = ";
temp -= (s[0]*1000 + s[1]*100+s[2]*10 +s[3]) ;
printf("%04d\n" ,temp);
x =temp ;
}
}