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;
}