1019 数字黑洞 (20 分) 给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。
例如,我们从6767开始,将得到
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174 7641 - 1467 = 6174 … …
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。
输入格式: 输入给出一个 (0,10^4 ) 区间内的正整数 N。
输出格式: 如果 N 的 4 位数字全相等,则在一行内输出 N - N = 0000;否则将计算的每一步在一行内输出,直到 6174 作为差出现,输出格式见样例。注意每个数字按 4 位数格式输出。
思路:模拟这个过程,主要是记得补全,做加减肯定要转化为int类型,然后得到新的最大值最小值。 我们有两种思路,一是变字符串,然后排序,最大从大到小,字符串可以直接+,然后得到后转化为int。
注意格式,前面要补0 code
#include<bits/stdc++.h>
using namespace std;
int ans;
int res;
int last;
int cmpp(char a,char b){
return a > b;
}
int max_trans(string ss){
ans = 0;
sort(ss.begin(),ss.end(),cmpp);
// cout<<"max__"<<ss<<endl;
for(int i=0;i<ss.size();i++){
ans += (ss[i]-'0');
ans *= 10;
}
return ans/10;
}
int min_trans(string ss){
ans = 0;
sort(ss.begin(),ss.end());
for(int i=0;i<ss.size();i++){
ans += (ss[i]-'0');
ans *= 10;
}
return ans/10;
}
bool check(string ss){
int l = ss.size();
for(int i=1;i<l;i++){
if(ss[i]!=ss[i-1]){
return false;
}
}
return true;
}
string too_string(int n){
int pos = n;
string s1;
while(pos!=0){
res = pos % 10;
pos /=10;
s1 += (res + '0');
}
reverse(s1.begin(),s1.end());
return s1;
}
int main(){
string s;
cin>>s;
if(check(s)){
cout<<setw(4)<<setfill('0')<<s;
cout<<" - ";
cout<<setw(4)<<setfill('0')<<s;
cout<<" = "<<"0000"<<endl;
}
else{
string s0 = s;
if(s0.size()==3) s0 = "0" + s0;
else if(s0.size()==2) s0 = "00" + s0;
else if(s0.size()==1) s0 = "000" + s0;
while(1){
res = max_trans(s0)- min_trans(s0);
cout<<setw(4)<<setfill('0')<<max_trans(s0);
cout<<" - ";
cout<<setw(4)<<setfill('0')<<min_trans(s0);
cout<<" = ";
cout<<setw(4)<<setfill('0')<<res<<endl;
if(res == 6174) break;
s0 = too_string(res);
if(s0.size()==3) s0 = "0" + s0;
else if(s0.size()==2) s0 = "00" + s0;
else if(s0.size()==1) s0 = "000" + s0;
//cout<<"s0 === "<<s0<<endl;
}
}
return 0;
}
法二:看了别的大佬的code,我们其实可以开一个数组存这几个数字,然后也是对这个数组排序,这样一来问题就简化了很多,不用来回转化,考虑各种补全。
//1019
#include <iostream>
#include <algorithm>
using namespace std;
int cmp(int a,int b){ //max to min
return a>b?1:0;
}
int main(){
int n,a[4]={0},b,c,t; cin>>n;
t=n;
do{
a[0]=t/1000;
a[1]=t%1000/100;
a[2]=t%1000%100/10;
a[3]=t%10;
sort(a,a+4,cmp);
b=a[0]*1000 +a[1]*100+a[2]*10+a[3];
sort(a,a+4); //min to max
c=a[0]*1000 +a[1]*100+a[2]*10+a[3];
t=b-c;
printf("%04d - %04d = %04d\n",b,c,t);
}while(t!=6174&&t!=0000);
return 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有