PAT - Class B 1019 Digital Black Hole

1019. Digital black hole (20)

time limit
100 ms
memory limit
65536 kB
code length limit
8000 B
Judgment procedure
Standard
author
CHEN, Yue

Given any 4-digit positive integer whose digits are not exactly the same, if we first sort the 4 numbers non-increasingly, then non-decreasingly, and then subtract the 2nd number from the 1st number, we will get a new number. Keep doing this over and over again, and we'll soon stop at 6174, known as the "digital black hole", the magic number also known as the Kaprekar constant.

For example, if we start with 6767, we will get

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

Now, given any 4-digit positive integer, write a program to demonstrate the process of reaching a black hole.

Input format:

Input gives a positive integer N in the interval (0, 10000).

Output format:

If the 4 digits of N are all equal, output "N - N = 0000" in one line; otherwise, output each step of the calculation in one line until 6174 appears as the difference, see the example for the output format. Note that each number is output in 4-digit format.

Input sample 1:
6767
Sample output 1:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
Input sample 2:
2222
Sample output 2:
2222 - 2222 = 0000


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

int main(){
	int arr[4], years;
	scanf("%d", &ans);
	arr[0] = years / 1000;  
    arr[1] = years / 100% 10;  
    arr[2] = years / 10% 10;  
    arr[3] = ans % 10;
	while(ans != 0){
		sort(arr, arr + 4);
		int a = arr[3] * 1000 + arr[2] * 100 + arr[1] * 10 + arr[0];
		int b = arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
		years = a - b;
		printf("%04d - %04d = %04d\n", a, b, ans);
		if(ans == 6174) break;
		arr[0] = years / 1000;  
	    arr[1] = years / 100% 10;  
	    arr[2] = years / 10% 10;  
	    arr[3] = ans % 10;
	}
	
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764613&siteId=291194637