pta 7-28 黑洞数 (20分)

黑洞数也称为陷阱数,又称“Kaprekar问题”,是一类具有奇特转换特性的数。

任何一个各位数字不全相同的三位数,经有限次“重排求差”操作,总会得到495。最后所得的495即为三位黑洞数。所谓“重排求差”操作即组成该数的数字重排后的最大数减去重排后的最小数。(6174为四位黑洞数。)

例如,对三位数207:

  • 第1次重排求差得:720 - 27 = 693;
  • 第2次重排求差得:963 - 369 = 594;
  • 第3次重排求差得:954 - 459 = 495;

以后会停留在495这一黑洞数。如果三位数的3个数字全相同,一次转换后即为0。

任意输入一个三位数,编程给出重排求差的过程。

输入格式:

输入在一行中给出一个三位数。

输出格式:

按照以下格式输出重排求差的过程:

序号: 数字重排后的最大数 - 重排后的最小数 = 差值

序号从1开始,直到495出现在等号右边为止。

输入样例:

123

输出样例:

1: 321 - 123 = 198
2: 981 - 189 = 792
3: 972 - 279 = 693
4: 963 - 369 = 594
5: 954 - 459 = 495
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <cmath>
#include <cstring>
#include <deque>
#include <queue>

using namespace std;

#define ios                    \
  ios::sync_with_stdio(false); \
  cin.tie(0);                  \
  cout.tie(0)
#define ll long long
#define met(a,b) memset(a,b,sizeof(a))

const int N = 1010;
int n,cnt;

void f(int x){
	// if(x==495){
	// 	printf("954 - 459 = 495");
	// }
	if(x<100){
		x=x*10;
	}
	int sum1=0,sum2=0;
	int arr[N]={0};
	int i=0;
	while(x!=0){
		arr[i++]=x%10;
		x=x/10;
	}
	sort(arr,arr+i);
	for(int j=0;j<i;j++){
		sum1+=arr[j]*pow(10,j);
	}
	for(int j=0;j<i;j++){
		sum2+=arr[j]*pow(10,i-j-1);
	}
	printf("%d - %d = %d\n",sum1,sum2,sum1-sum2);
	n=sum1-sum2;
}
int main(){
    // freopen("D:\\YJ.txt","r",stdin);
	cin>>n;
	while(1){
		printf("%d: ",++cnt);
		f(n);
		if(n==495){
			break;
		}
	}
	// cout<<res(n);
	// cout<<a<<"asdasd";
    ios;
    return 0;
}
发布了32 篇原创文章 · 获赞 7 · 访问量 822

猜你喜欢

转载自blog.csdn.net/Young_Naive/article/details/104027655