1019 數字黑洞 (20分)
題目地址:https://pintia.cn/problem-sets/994805260223102976/problems/994805302786899968
給定任一個各位數字不完全相同的 4 位正整數,如果我們先把 4 個數字按非遞增排序,再按非遞減排序,然后用第 1 個數字減第 2 個數字,將得到一個新的數字,一直重復這樣做,我們很快會停在有“數字黑洞”之稱的 6174,這個神奇的數字也叫 Kaprekar 常數,
例如,我們從6767開始,將得到
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174 7641 - 1467 = 6174 ... ...
現給定任意 4 位正整數,請撰寫程式演示到達黑洞的程序,
輸入格式:
輸入給出一個 (0,10000) 區間內的正整數 N,
輸出格式:
如果 N 的 4 位數字全相等,則在一行內輸出 N - N = 0000;否則將計算的每一步在一行內輸出,直到 6174 作為差出現,輸出格式見樣例,注意每個數字按 4 位數格式輸出,
輸入樣例
6767
輸出樣例
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174
我的理解
邏輯也很清晰,輸入字串,排序,反轉,轉化為數值,計算,然后在轉化為字串,回圈往復,
- 輸入的范圍是(0, 10000),有可能只輸入一位數字,此時需要對輸入進行預處理,前面補0,例如輸入3,則需要處理為0003,看題意說給定任意4位正整數,以為會是(999,10000),但是輸入格式又給我否定了,
- 在計算“黑洞”的程序中,也有可能出現前綴為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;
}
更改程序
- 忽略了對輸入以及計算“黑洞”程序中可能出現的前綴為0的情況,
- while判斷起初判斷了差值x != 6174,還寫了 x!= 0的判斷條件,并且使用了|| ,導致出現死回圈,超時,
and 2020新年快樂、、、
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/102313.html
標籤:其他
上一篇:無法解決:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1
