題目地址: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
#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; }
and 2020新年快樂、、、string