【C++】1876 - Digital Black Hole

question

For any four-digit positive integer (except those with the same four digits), if the digits are combined into a maximum and minimum number, subtract the two numbers and repeat this process, we will get 6174.

Insert image description here

1. Analyze the problem

  1. Known: four-digit positive integer
  2. Unknown: The process of getting 6174
  3. Relationship: Each digit forms a maximum number and a minimum number, and the two numbers are subtracted.

2. Define variables

//二、数据定义
	int n; 

3. Enter data

	//三、数据输入 
	cin>>n;

4.Data calculation

Because the number needs to be reassembled, disassembly is definitely used, and short division is preferred.
temp: actually the value of n, used for short division iteration loops.
a[4]: An array is used here to store the number obtained by splitting.
c: Record array subscript.

int temp=n,max,min,result,c=0,a[4]={
    
    0};
		while(temp>0){
    
    
			a[c]=temp%10;
			++c; 
			temp/=10;
		}

If I need to form a maximum number max and a minimum number min, then the way I think of is to sort the array, then the maximum number and the minimum number will be known.

for(int i=0;i<3;i++){
    
    
			for(int j=0;j<3-i;j++){
    
    
				if(a[j]>a[j+1]){
    
    
					int t=a[j];
					a[j]=a[j+1];
					a[j+1]=t;
				}
			}
		}
max=a[3]*1000+a[2]*100+a[1]*10+a[0];
min=a[0]*1000+a[1]*100+a[2]*10+a[3];

Subtract the result of the two numbers and output it.

result=max-min;
cout<<max<<"-"<<min<<"="<<result<<endl;

Repeat this process until this number = 6174.

//四、数据计算 
	while(6174!=n){
    
    
	
		n=result;
	}

5. Output results

Complete code.

#include<iostream>
using namespace std;
int main(){
    
    
	//一、分析问题
	//已知:四位正整数
	//未知:得到6174的过程 
	//关系:各位数字组成一个最大数和最小数,两数相减

	
	//二、数据定义
	int n; 
	

	//三、数据输入 
	cin>>n;
	
	//四、数据计算 
	while(6174!=n){
    
    
		int temp=n,max,min,result,c=0,a[4]={
    
    0};
		while(temp>0){
    
    
			a[c]=temp%10;
			++c; 
			temp/=10;
		}
		
		for(int i=0;i<3;i++){
    
    
			for(int j=0;j<3-i;j++){
    
    
				if(a[j]>a[j+1]){
    
    
					int t=a[j];
					a[j]=a[j+1];
					a[j+1]=t;
				}
			}
		}
		max=a[3]*1000+a[2]*100+a[1]*10+a[0];
		min=a[0]*1000+a[1]*100+a[2]*10+a[3];
		result=max-min;
		cout<<max<<"-"<<min<<"="<<result<<endl;
		n=result;
	}
	

	//五、输出结果 
	return 0;	
}

Guess you like

Origin blog.csdn.net/qq_39180358/article/details/135216074