解题思路:具体的思路参考注释

注意事项:无

参考代码1(C++版):

#include <stdio.h>
#include <algorithm>	//调用sort排序函数,纯C的话需要自定义sort函数 
using namespace std;
int main(){
	int n,sum=0;
	scanf("%d",&n);	//读取四位数 
	int str[4];	//存储四位数 
	while(n!=6174){	//判断是否符合条件 
		int m = n;
		int i = 0;
		while(m!=0){	//将四位数拆分为单个字符存储到数组 
			str[i]=m%10;
			m /= 10;
			i++;
		}
		sort(str,str+4);	//排序 
		int s1 = str[0] * 1000 + str[1] * 100 + str[2] * 10 + str[3];	//默认递增排序,最小值 
		int s2 = str[3] * 1000 + str[2] * 100 + str[1] * 10 + str[0];	//最大值 
		n = s2 - s1;	//新数 
		sum++;	//统计次数 
	}
	printf("%d\n",sum);
	return 0;
}

参考代码2(纯C版):

#include <stdio.h>

int cap(const void *a, const void *b){
    return *(int*)b - *(int*)a;
}

int stor(int n){
    int zoo[4] = {n/1000, n%1000/100, n%100/10, n%10};
    qsort(zoo, 4, sizeof(int), cap);
    return zoo[0] * 1000 + zoo[1] * 100 + zoo[2] * 10 + zoo[3];
}

int rever(int n){
    return n/1000 + n%1000/100 * 10 + n%100/10 * 100 + n%10 * 1000;
}

int main(){
    int n, sum = 0;
    scanf("%d", &n);
    do{
        n = stor(n);
        sum++; 
        n = n - rever(n);
    }while(n != 0 && n != 6174) ;
    printf("%d\n", sum);
    return 0;
}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答

代码解释器

  评论区