Acm 57 6174问题

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    


public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int m = scan.nextInt();
		int n;
		int[] num;
		int nextn;
		int count = 1;
		while(m-- > 0){
			n = scan.nextInt();
			nextn = n;
			num = paixu(n);
			while(num[0] - num[1] != nextn){
				++count;
				nextn = num[0] - num[1];
				num = paixu(nextn);
			}
			System.out.println(count);
			count = 1;
		}
	}
	static int[] paixu(int ma){
		int[] num = new int[2];
		char[] data = Integer.toString(ma).toCharArray();
		char max ;
		for(int i = 0; i < data.length-1; ++i){
			for(int j = i + 1; j < data.length ; ++j){
				if(data[i] < data[j]){
					max = data[i];
					data[i] = data[j];
					data[j] = max;
				}
			}
		}
		num[0] = Integer.parseInt(String.valueOf(data));
		Arrays.sort(data);
		num[1] = Integer.parseInt(String.valueOf(data));
		return num;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值