题目地址: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