描述
假设你有一个各位数字互不相同的四位数,把所有的数字从大到小排序后得到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
代码如下
public class Pa {
public static void main(String[] args){
qS(1234);
}
public static void qS(int num){
int count = 0;
int[] arr = new int[4];
while(num!=6174){
arr[0] = num/1000;
arr[1] = num/100%10;
arr[2] = num/10%10;
arr[3] = num%10;
int tmp = 0;
for(int j=0;j<arr.length-1;j++){
for(int i=0;i<arr.length-1;i++){
if(arr[i]>arr[i+1]){
tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
}
}
int max = arr[0] + arr[1]*10 + arr[2]*100 + arr[3]*1000;
int min = arr[0]*1000 + arr[1]*100 + arr[2]*10 + arr[3];
count++;
System.out.println("第"+count+"次运算为:"+max+"-"+min+"="+(max-min));
num = max-min;
}
System.out.println(count);
}
}