【PAT】A1069 The Black Hole of Numbers (20分)

  • PAT
  • 2022-07-15 23:12:50

题目

【PAT】A1069 The Black Hole of Numbers (20分)
【PAT】A1069 The Black Hole of Numbers (20分)

解决

思路

  • 用一个数组存放每一位,排序后可以得到min, max
  • max-min=x
  • 循环计算max-min=x
  • 如果x == 6174 or x== 0停止循环

实现

Code1

#include<cstdio>
#include<algorithm>
using namespace std;

bool cmp(int a, int b){
	return a < b;
}

int main(){
	int x;
	scanf("%d", &x);
	int num[4];
	
	while(true){
		for(int i=0; i<4; i++){
			num[i] = x % 10;
			x /= 10;
		}
		sort(num, num+4);
		int min = 0, max = 0;
		for(int i=0, j=3; i<4, j>=0; i++, j--){
			min = min*10+num[i];
			max = max*10+num[j];
		}
		x = max - min;
		printf("%04d - %04d = %04d\n", max, min, x);
		if(x == 6174 || x == 0) break;
	}
	
	return 0;
}

猜你喜欢