[PAT解题报告] The Black Hole of Numbers
简单题,按照题目说的,把一个四位数各位数字由大到小排,再由小到大排,排好之后求差(允许有首0),得到的结果继续这么做,直到出现6174或者0000为止。
C/C++ 可以方便用sscanf,
sprintf从字符串里读数,以及把数写进字符串。所以就是一个while循环了。照着模拟就好。
#include <cstdio> #include <cstring> #include <string> #include <algorithm> using namespace std; char s[6]; int main() { int n; for (scanf("%d",&n);;) { int x,y; sprintf(s, "%04d", n); sort(s, s + 4); reverse(s, s + 4); printf("%s - ",s); sscanf(s, "%d", &x); reverse(s, s + 4); printf("%s",s); sscanf(s, "%d", &y); printf(" = %04d\n",n = x - y); if ((n == 0) || (n == 6174)) { break; } } return 0; }
原题代码: http://www.patest.cn/contests/pat-a-practise/1069