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

相關文章
相關標籤/搜索