[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

相关推荐

星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务