1019. 数字黑洞
给定任⼀个各位数字不完全相同的4位正整数,如果我们先把4个数字按⾮递增排序, 再按⾮递减排序,然后⽤第1个数字减第2个数字,将得到⼀个新的数字。⼀直重复 这样做,我们很快会停在有“数字⿊洞”之称的6174,这个神奇的数字也叫Kaprekar常数。
例如,我们从6767开始,将得到
7766 – 6677 = 1089
9810 – 0189 = 9621
9621 – 1269 = 8352
8532 – 2358 = 6174
7641 – 1467 = 6174
… …
现给定任意4位正整数,请编写程序演示到达⿊洞的过程。
输⼊格式:
输⼊给出⼀个(0, 10000)区间内的正整数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
#include<bits/stdc++.h>
using namespace std;
int main(){
// a为被减数,b为减数,temp为结果
string a,b,temp;
cin>>a;
while(1){
//当位数不足4位时,在前面补0
while(a.size()<4) a='0'+a;
//从小到大排序,那么排序后的结果就是减数b
sort(a.begin(),a.end());
b=a;
//翻转后的结果就是最大的数,即被减数a
reverse(a.begin(),a.end());
//要计算结果时,必须要先把被减数和减数转化为int型,才能计算
int a1=stoi(a);
int b1=stoi(b);
//将int型转化为string型
temp=to_string(a1-b1);
//当结果位数不足4位时,补0
while(temp.size()<4) temp='0'+temp;
cout<<a<<" - "<<b<<" = "<<temp<<endl;
if(temp=="0000") break;
if(temp=="6174") break;
a=temp;
}
return 0;
}
解释:
stoi函数:把数字字符串转换成int输出