PAT乙级1019

1019 数字黑洞 (20分)

题目地址:https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968ios

给定任一个各位数字不彻底相同的 4 位正整数,若是咱们先把 4 个数字按非递增排序,再按非递减排序,而后用第 1 个数字减第 2 个数字,将获得一个新的数字。一直重复这样作,咱们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。spa

例如,咱们从6767开始,将获得code

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...

现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。排序

输入格式:

输入给出一个 (0,10000) 区间内的正整数 N。ci

输出格式:

若是 N 的 4 位数字全相等,则在一行内输出 N - N = 0000;不然将计算的每一步在一行内输出,直到 6174 做为差出现,输出格式见样例。注意每一个数字按 4 位数格式输出。字符串

输入样例

6767

输出样例

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

个人理解

逻辑也很清晰,输入字符串,排序,反转,转化为数值,计算,而后在转化为字符串,循环往复。get

  1. 输入的范围是(0, 10000),有可能只输入一位数字,此时须要对输入进行预处理,前面补0,例如输入3,则须要处理为0003,看题意说给定任意4位正整数,觉得会是(999,10000),可是输入格式又给我否认了。
  2. 在计算“黑洞”的过程当中,也有可能出现前缀为0的状况,此时也要作处理。

代码段

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
string sortN(string N);
int main() {
    string N;
    cin >> N;
    string temp = N;
    if (temp.length() == 3) {
        temp = temp.insert(0, "0");
    } else if (temp.length() == 2) {
        temp = temp.insert(0, "00");
    } else if (temp.length() == 1) {
        temp = temp.insert(0, "000");
    }
    string m = sortN(temp);
    string n = m;
    reverse(n.begin(), n.end());
    int a, b, x = 1;
    while (x != 6174) {
        a = stoi(m);
        b = stoi(n);
        x = a - b;
        if (x == 0) {
            // 格式控制
            printf("%04d - %04d = %04d\n", a, b, x);
            break;
        }
        printf("%04d - %04d = %04d\n", a, b, x);
        // 类型转化,忘记处理前缀为0的状况,例如N = 9998时
        string temp = to_string(x);
        if (temp.length() == 3) {
            temp = temp.insert(0, "0");
        } else if (temp.length() == 2) {
            temp = temp.insert(0, "00");
        } else if (temp.length() == 1) {
            temp = temp.insert(0, "000");
        }
        m = sortN(temp);
        n = m;
        reverse(n.begin(), n.end());
    }
    return 0;
}

string sortN(string N) {
    for (int i = 0; i < N.length(); i++) {
        for (int j = i + 1; j < N.length(); j++) {
            if (N[i] < N[j]) {
                char temp = N[i];
                N[i] = N[j];
                N[j] = temp;
            }
        }
    }
    return N;
}

更改过程

  1. 忽略了对输入以及计算“黑洞”过程当中可能出现的前缀为0的状况。
  2. while判断起初判断了差值x != 6174,还写了 x!= 0的判断条件。而且使用了|| ,致使出现死循环,超时。

and 2020新年快乐、、、string

相关文章
相关标签/搜索