[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
全部评论
nb 还能这么做。学到了
点赞 回复 分享
发布于 2016-02-28 22:52

相关推荐

理智的马里奥不愿再收感谢信:这小米咱是非去不可了是吗?
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务