给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174
,这个神奇的数字也叫 Kaprekar 常数。
例如,我们从6767
开始,将得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。
输入格式:
输入给出一个 ( 区间内的正整数 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
思路1:
用string接收输入,当数字不足四位数的时候,用0补高位
将字符串数字从高到低排序,再从低到高排序,分别转换成整型数字
得到的差值再转换成字符串,不足四位数高位补0,满足条件则退出循环。
需要注意的是,当差值为6174或者0000的时候要结束循环,当输入为6174的时候也要进行计算,所以这里用do while。
思路2:
用int接收输入,和思路1差不多,将输入转化成字符串,补0
然后做两次排序,转成整形数字再相减,得到差值
最用用%4d占位符,输出整形数字即可
C++实现:
思路1
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cctype>
#include <unordered_map>
using namespace std; bool cmp(char a, char b)
{
return a > b; //从高到低排序
} int main()
{
int result = ;
string N;
cin >> N;
N.insert(, - N.size(), '');
do
{
string a = N;
string b = N;
sort(a.begin(), a.end(), cmp);
sort(b.begin(), b.end());
result = stoi(a) - stoi(b);
N = to_string(result);
N.insert(, - N.size(), '');
cout << a << " - " << b << " = " << N << endl;
} while (N != "" && N != "");
return ;
}
思路2
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cctype>
#include <unordered_map>
using namespace std; bool cmp(char a, char b)
{
return a > b;
} int main()
{
int N;
int result = ;
cin >> N;
string s = to_string(N);
do
{
s.insert(, - s.size(), '');
sort(s.begin(), s.end(), cmp);
int a = stoi(s);
sort(s.begin(), s.end());
int b = stoi(s);
result = a - b;
printf("%04d - %04d = %04d\n",a,b,result);
s = to_string(result);
} while (result != && result != ); return ;
}
Java实现:
小结:
1. str.insert(, - s.size(), ''); 是用来高位补0的,
basic_string& insert( size_type index, size_type count, CharT ch ); 意思是,在index处插入count个字符ch
当字符串str为 22的时候,str.size() = 2, 所以在 index = 0处插入 4 - 2 = 2 个字符 '0'
这样就实现了高位补0
想了想,也不需要在高位补0,只要插入相应个数的0就可以了,毕竟需要对字符串进行排序,在哪里插入0都无所谓了