6174问题
时间限制:1000 ms | 内存限制:65535 KB
难度:2
描述
假设你有一个各位数字互不相同的四位数,把所有的数字从大到小排序后得到a,从小到大后得到b,然后用a-b替换原来这个数,并且继续操作。例如,从1234出发,依次可以得到4321-1234=3087、8730-378=8352、8532-2358=6174,又回到了它自己!现在要你写一个程序来判断一个四位数经过多少次这样的操作能出现循环,并且求出操作的次数
比如输入1234执行顺序是1234->3087->8352->6174->6174,输出是4
输入
第一行输入n,代表有n组测试数据。
接下来n行每行都写一个各位数字互不相同的四位数
输出
经过多少次上面描述的操作才能出现循环
样例输入
1
1234
样例输出
4
来源
[张洁烽]原创
问题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=57
代码:
#include <iostream>
#include <stdio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//0123 a[]= {3,2,1,0}
int op(int x){
//1.将数分割为a[3]a[2]a[1]a[0]
int a[4];
for(int i=0;i<4;i++){
a[i] = x%10;
x/=10;
}
//2.对4个数进行排序(选择排序)
for(int i=0;i<3;i++){
int index = i;
for(int j=i+1;j<4;j++){
if(a[j] < a[index]){
index = j ;
}
}
int tmp = a[index];
a[index] = a[i];
a[i] = tmp;
}
int ans1=0,ans2=0;
int c = 1;
for(int i=0;i<4;i++){
ans1+=a[i]*c;
ans2+=a[3-i]*c;
c*=10;
}
//printf("%d %d\n",ans1,ans2);
return ans1-ans2;
}
int main(int argc, char** argv) {
int n;
scanf("%d",&n);
while(n--) {
int tmp;
scanf("%d",&tmp);
int count = 1;
while(tmp!=op(tmp)){
count++;
tmp = op(tmp);
//printf("%d",tmp);
}
printf("%d\n",count);
}
return 0;
}
收获:
合并一些公共的部分,提高抽象的层次,不仅使得代码更加简洁,而且减小了错误的概率。