XTU OJ 1191 Magic

Description

题目描述

6174是一个神奇的数字,你将一个4位数n(只要这4位数码不完全一样)所有数码按升序和降序分别得到A和B,取n=B-A,如果n不为6174的话,继续迭代上面的过程,直到n为6174。 比如

no. n    A    B 
0   1000 0001 1000
1   0999 0999 9990
2   8991 1899 9981
3   8082 0288 8820
4   8532 2358 8532
5   6174
 
请问需要迭代多少次才能达到6174?

输入

每行一个4位整数n,并且n的所有数码不完全相同。如果n=0表示输入结束,不需要处理。

输出

每行输出一个样例的结果。

样例输入
1000
6174
0

样例输出
5
0

这一题就考察了一个排序,A是升序的,从小到大,B是降序的,从大到小

所以每次把n拆了放在数组中然后进行排序,再转化为A,B即可

方法一:qsort排序(可以去看看文章这个怎么用)

#include<stdio.h>
#include<stdlib.h>
int cmp(const void* p1,const void* p2)
{//从小到大排序
	return *(int*)p1 - *(int*)p2;
}
int main()
{
	int n;
	while(scanf("%d", &n)&&n!=0){
		int cnt=0;
		if(n==6174){
			printf("%d\n", cnt);
			continue;
		}else{
			while(n!=6174){
				int s[4];
				s[0] = n%10;//个位
				s[1] = n/10%10;//十位
				s[2] = n/100%10;//百位
				s[3] = n/1000;//千位
				qsort(s,4,sizeof(s[0]),cmp);
				int b = s[3]*1000 + s[2]*100 + s[1]*10 + s[0];
				int a = s[0]*1000 + s[1]*100 + s[2]*10 + s[3];
				n = b-a;
				cnt++;
			}
			printf("%d\n", cnt);
		}
		
		
	}
	return 0;
}

方法二:冒泡排序

#include<stdio.h>
int main()
{
    int n;
    while(scanf("%d", &n)==1&&n!=0){
        int x[5];
        int cnt=0;//计数 
        while(n!=6174){
            int a,b;
            x[0] = n/1000;//第4位
            x[1] = n%1000/100;//3
            x[2] = n%100/10;//2
            x[3] = n%10;//1
            //排序x【i】
            for(int i=0;i<4;i++){//循环四次,每次排好一个数
                for(int j=0;j<4-i-1;j++){
                    if(x[j]>x[j+1]){
                        int temp = x[j];
                        x[j] = x[j+1];
                        x[j+1] = temp;
                    }
                }
            }
            //排完0-3依次变大 
            a = x[0]*1000+x[1]*100+x[2]*10+x[3];
            b = x[3]*1000+x[2]*100+x[1]*10+x[0];
            n = b - a;
            cnt++;
        }
        printf("%d\n", cnt);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值