PAT 甲级 1069 The Black Hole of Numbers (20 分)(内含别人string处理的精简代码)

时间:2023-03-09 02:22:06
PAT 甲级 1069 The Black Hole of Numbers (20 分)(内含别人string处理的精简代码)
1069 The Black Hole of Numbers (20 分)

For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 -- the black hole of 4-digit numbers. This number is named Kaprekar Constant.

For example, start from 6767, we'll get:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...

Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

Input Specification:

Each input file contains one test case which gives a positive integer N in the range (.

Output Specification:

If all the 4 digits of N are the same, print in one line the equation N - N = 0000. Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.

Sample Input 1:

6767

Sample Output 1:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

Sample Input 2:

2222

Sample Output 2:

2222 - 2222 = 0000
作者: CHEN, Yue
单位: 浙江大学
时间限制: 200 ms
内存限制: 64 MB
代码长度限制: 16 KB

题意:

给一个数组n,先对各个数字位从大到小排序得到a,然后逆置得到b,计算a-b,得到c,重复上述过程,直到得到6174,或者,对于特例,四个数字位完全相同,那么输出0000。

题解:

刚开始输入的数字可能不足四位要自动补0 以后的结果可能也不足四位都要自动补0

结果是0或者6174都是要退出的

一开始没考虑到6174,测试点5没过,后来想到了

AC代码:

#include<iostream>
#include<algorithm>
using namespace std;
int n;
int a[];
int main(){
cin>>n;
int big=;
int small=;
int x=n;
int k=,f;
if(x==){
printf("7641 - 1467 = 6174");
return ;
}
while(x!=){
k=;
big=;
small=;
while(x>=){
a[++k]=x%;
x/=;
}
a[++k]=x;
while(k<){
a[++k]=;
}
sort(a+,a++);
for(int i=;i<=;i++){
big=big*+a[-i];
small=small*+a[i];
}
x=big-small;
printf("%04d - %04d = %04d\n",big,small,x);
if(x==) break;
}
return ;
}

更简洁的string处理的代码:

#include<bits/stdc++.h>
using namespace std;
bool cmp(char a,char b)
{
return a>b;
}
int main(void)
{
string s;
cin>>s;
s.insert(,-s.size(),'');
do{
string a=s,b=s;
sort(a.begin(),a.end(),cmp);
sort(b.begin(),b.end());
int diff=stoi(a)-stoi(b);
s=to_string(diff);
s.insert(,-s.size(),'');
cout<<a<<" - "<<b<<" = "<<s<<endl;
}while(s!=""&&s!="");
return ; ————————————————
版权声明:本文为****博主「Imagirl1」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.****.net/Imagirl1/article/details/82261213