1019 digital black hole (20 points) detailed idea test case

给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。

例如,我们从6767开始,将得到

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。

输入格式:
输入给出一个 (0,104
​​ ) 区间内的正整数 N。

输出格式:
如果 N 的 4 位数字全相等,则在一行内输出 N - N = 0000;否则将计算的每一步在一行内输出,直到 6174 作为差出现,输出格式见样例。注意每个数字按 4 位数格式输出。

输入样例 16767
输出样例 17766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
输入样例 22222
输出样例 22222 - 2222 = 0000

  1. Question meaning
    Enter a four-digit number, but it may be less than four
    . The number obtained by the difference between the two sequences will end if it is 6174.
    Otherwise, the difference will be calculated as a new number.
    In addition, if the four-digit number is the same, output 0000.
    Note that It is 4 digits, less than zero padding,
    output operation process
  2. Idea
    Input a string, convert it into 4 numbers and store it in an array a,
    judge whether the input is 4 digits, less than 4 digits, the array corresponds to bit 0;
    judge whether the four digits are the same;
    use printf output to control the output Number of digits;
    with the help of the sort function, you can get the minus and minus, convert them to numbers, calculate the difference, and re-store the difference numbers in the array;
    loop judgment until the result is satisfied
  3. Code
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
bool cmp1(int a,int b){
    
    
	return a>=b;
}
	
bool cmp2(int a,int b){
    
    
	return a<=b;
}
//字符串转换为数字 
int StrNum(string s){
    
    
	int i;
	int num=0;
	for(i=0;i<4;i++){
    
    
		num=num*10+(s[i]-'0');
	}
	return num;
}	

int main(){
    
    
	int i;
	int x=0;
	string s;	//字符串输入 
	cin>>s;
	int a[4];	//存储到数组中
	//当输入不足4位数时,补零 测试点2 3 4 
	if(s.length()<4){
    
    
		for(i=0;i<s.length();i++){
    
    
			a[i]=s[i]-'0';
		}
		for(i=s.length();i<4;i++){
    
    
			a[i]=0;
		}
	}
	else{
    
    
		for(i=0;i<4;i++){
    
    
			a[i]=s[i]-'0';
		}
	}
	//当各位相同,输出0000 
	if(s[0]==s[1]&&s[1]==s[2]&&s[2]==s[3]){
    
    
		x=StrNum(s);
		printf("%04d - %04d = 0000",x,x);	//注意printf输出,便于解决4位输出问题 
	}
	else{
    
    
		//各位不完全相同,到x=6174之前循环操作 
		while(x!=6174){
    
    
			x=0;
			int y=0;
			sort(a,a+4,cmp1);	//非增排列 
			for(i=0;i<4;i++){
    
    
				x=x*10+a[i];
			}
			printf("%04d - ",x);
			sort(a,a+4,cmp2);
			for(i=0;i<4;i++){
    
    
				y=y*10+a[i];
			}
			printf("%04d = ",y);
			x=x-y;
			printf("%04d\n",x);
			int k=x;
			for(i=0;i<4;i++){
    
    
				a[i]=k%10;
				k=k/10;
			}
		}
	}
	return 0;
}
  1. Test case 2 3 4
    input does not meet 4 digits
10
1000 - 0001 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174

Guess you like

Origin blog.csdn.net/weixin_44549439/article/details/112907384