一、题目描述
给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174
,这个神奇的数字也叫 Kaprekar 常数。
例如,我们从6767
开始,将得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。
输入格式:
输入给出一个 (0,104) 区间内的正整数 N。
输出格式:
如果 N 的 4 位数字全相等,则在一行内输出 N - N = 0000
;否则将计算的每一步在一行内输出,直到 6174
作为差出现,输出格式见样例。注意每个数字按 4
位数格式输出。
输入样例 1:
6767
输出样例 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
输入样例 2:
2222
输出样例 2:
2222 - 2222 = 0000
二、思路分析
给定四位数字,可以将该数字的每一位数字拿出来存储在一个动态数组里,利用sort函数排序,经过计算得出把该数字升序或者降序的效果(max、min);再利用while循环,比较max、min;按照题目所给格式输出即可。
第一个要注意的是格式的控制。一定是四位,不够要在前面补0;
第二个要注意的是每输出一次,动态数组的内容应该清空、更新。
三、题解代码以及提交截图
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main()
{
int num,max,min;
int temp;
cin >> num;
vector<int> list;
list.push_back(num / 1000);
list.push_back(num / 100 % 10);
list.push_back(num / 10 % 10);
list.push_back(num % 10);
while(true)
{
sort(list.begin(),list.end());
max = 1000 * list[3] + 100 * list[2] + 10 * list[1] + list[0];
min = 1000 * list[0] + 100 * list[1] + 10 * list[2] + list[3];
temp = max -min;
if(max == min){
cout << setw(4)<<setfill('0') << max << " - " << setw(4)<<setfill('0') << max << " = " << "0000";
return 0;
}
else{
cout << setw(4)<<setfill('0')<< max << " - " << setw(4)<<setfill('0') << min << " = " << setw(4)<<setfill('0')<< temp << endl;
if(temp == 6174){
return 0;
}
list.clear();
list.push_back(temp / 1000);
list.push_back(temp/ 100 % 10);
list.push_back(temp / 10 % 10);
list.push_back(temp % 10);
}
}
}
四、附优(chao)秀(duan)题解代码
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(char a, char b) {return a > b;} //如果输入的数字不够四位一定要补齐!
int main()
{
string s;
cin >> s;
s.insert(0, 4 - s.length(), '0');
do {
string a = s, b = s;
sort(a.begin(), a.end(), cmp);//sort函数用法
sort(b.begin(), b.end());
int result = stoi(a) - stoi(b);
s = to_string(result);
s.insert(0, 4 - s.length(), '0');//补位
cout << a << " - " << b << " = " << s << endl;
} while (s != "6174" && s != "0000");
return 0;
}