PAT乙级1019

题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968

题解

根据用户输入或者每次的计算结果,生成大数和小数,然后输出计算过程,一直循环该过程;当结果为0或6174时,循环终止。

刚开始我有一个测试点是没过的,参考了https://blog.csdn.net/qunqunstyle99/article/details/83189284才过了全部测试点。所以写ACM题我们得自己会猜一些边界条件,正确理解题意,然后写代码。

// PAT BasicLevel 1019
// https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

#define ARRSIZE 5
#define ARRLEN 4

int main()
{
    // 生成的大数和小数
    char big[ARRSIZE];
    char small[ARRSIZE];

    // 大数-小数
    int result;char res[ARRSIZE];
    
    // 获取用户输入的数字
    scanf("%d", &result);

    while (true){

        // 生成大数和小数
        sprintf(small, "%04d\0", result);
        sort(small, small + ARRLEN);
        strcpy(big, small);
        reverse(big, big + ARRLEN);

        // 计算大数-小数
        result = 0;
        for (int i = 0, diff; i < ARRLEN; i++)
        {
            result = result * 10 + big[i] - small[i];
        }

        // 输出结果
        printf("%s - %s = %04d\n", big, small, result);
        
        // 当结果为0或6174时程序结束
        sprintf(res, "%04d\0", result);
        if (!(strcmp(res, "0000\0") && strcmp(res, "6174\0")))
            break;
    }

    //system("pause");
    return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


posted @ 2019-08-06 15:30  臭咸鱼  阅读(145)  评论(0编辑  收藏  举报