Given a 4-digit positive integer with different digits, if we first rank the 4 digits in non increasing order, then rank them in non decreasing order, and then subtract the second digit from the first digit, we will get a new digit. We will soon stop at 6174, the "digital black hole", which is also called Kaprekar constant.
For example, starting with 6767, we will get
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
Given any 4-bit positive integer, please write a program to demonstrate the process of reaching the black hole.
Input format:
Enter to give a (0,10
4
The positive integer N in the interval.
Output format:
If the four digits of N are all equal, output N - N = 0000 in one line; otherwise, output each step of calculation in one line until 6174 appears as a difference. See the example for the output format. Note that each number is output in 4-digit format.
Enter example 1:
6767
Output example 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Enter example 2:
2222
Output example 2:
2222 - 2222 = 0000
Note the processing of 0 when calculating and outputting.
#include<iostream> #include<string> #include <sstream> #include <iomanip> using namespace std; void check(string& str) { switch (str.size()) { case 1: str = "000" + str; break; case 2: str = "00" + str; break; case 3: str = "0" + str; break; default: break; } } int func(int a) { int result; string str = to_string(a); check(str); string b = ""; for (int i = str.size() - 1; i >= 0; i--) b += str[i]; stringstream ss; ss << b; ss >> result; return result; } int sort(int a) { int result; string str = to_string(a); check(str); for (int i = 0; i < str.size() - 1; i++) for (int j = i + 1; j < str.size(); j++) { if (str[j] > str[i]) { int tmp = str[j]; str[j] = str[i]; str[i] = tmp; } } stringstream ss; ss << str; ss >> result; return result; } void print(int n) { int a, b; do { a = sort(n); b = func(a); if (a - b == 0) { cout << setw(4) << setfill('0') << a << " - " << setw(4) << setfill('0') << b << " = " << setw(4) << setfill('0') << (a - b) << endl; break; } cout << setw(4) << setfill('0') << a << " - " << setw(4) << setfill('0') << b << " = " << setw(4) << setfill('0') << (a - b) << endl; n = a - b; } while ((a - b) != 6174); } int main() { int n; cin >> n; print(n); return 0; }