PAT digital black hole c++ compilation

PAT digital black hole

Given any 4-digit positive integer whose digits are not exactly the same, if we first sort the 4 digits in non-increasing order, then sort in non-decreasing order, and then subtract the second digit from the first digit, we will get a new digital. Repeatedly doing this, we will soon stop at 6174, known as the "digital black hole", this magical number is also called Kaprekar's constant.

For example, if we start from 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, please write a program to demonstrate the process of reaching a black hole.

Input format:
Input gives a positive integer N in the interval (0,10
​4
​​).

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 a difference. See the example for the output format. Note that each number is output in a 4-digit format.

Input example 1:
6767

Output example 1:
7766-6677 = 1089
9810-0189 = 9621
9621-1269 = 8352
8532-2358 = 6174

Input example 2:
2222

Output sample 2:
2222-2222 = 0000

c++
#代码
#include
#include
#include <stdio.h>
using namespace std;

bool cmp(int a,int b){
return a>b;
}
void toarray(int n,int num[]){
for(int i=0;i<4;i++){
num[i]=n%10;
n=n/10;
}
}
int toint(int num[]){
int sum=0;
for(int i=0;i<4;i++){
sum=sum*10+num[i];
}
return sum;
}
int main()
{
int num[5];
int n;
cin>>n;
int a;
int b;
while(1){
toarray(n,num);
sort(num,num+4);
a=toint(num);
sort(num,num+4,cmp);
b=toint(num);
n=b-a;
printf("%04d - %04d = %04d\n",b,a,n);
if(n0||n6174)
break;
}
return 0;
}
Parsing: Among them, %04d in the output format of printf means: when outputting integer x, align the extra places to the left according to the space of 4 bits and replace them with 0.

Guess you like

Origin blog.csdn.net/weixin_43902941/article/details/105948797