黑洞数:将一个数各个位的数重排后最大数减去最小数,得到答案后继续执行上述操作,最终会得到一个固定的数,如,3位数的黑洞数是495,4位数的黑洞数是6174.

验证四位数的黑洞数是6174.

首先我们要获取一个四位数的各个位上的数值,将四个数值排序后,取得四位最大值和四位最小值,然后相减,直到结果是6174.

package _3InterestingInteger;

import java.util.Arrays;
/*
求黑洞数
 */

public class _3_5 {
    public static void main(String[] args) {
        for(int i=1000;i<=9999;i++){
            //如果每一位上的数值相同则跳出当前循环
            if(i%1111==0){
                System.out.println(i+"数字完全相同!");
                continue;
            }
            else{
                int count=0;//相减的次数
                int input=i;
                do{
                    input=fun(split(input));
                    count++;
                }while(input!=6174);

                if(input==6174){
                    System.out.println("计算了"+count+"次!");
                }
            }
        }

    }

    //分离出每一位,并且排序
    public static int[] split(int input){
        int[] a=new int[4];
        //获取千位数
        a[0]=input/1000;
        //获取百位数
        a[1]=input%1000/100;
        //获取十位数
        a[2]=input%100/10;
        //获取个位数
        a[3]=input%10;

        Arrays.sort(a);
        return a;
    }

    //分离后求出最大值和最小值并且相减
    public static int fun(int[] a){
        Arrays.sort(a);
        int min=a[0]*1000+a[1]*100+a[2]*10+a[3];
        int max=a[3]*1000+a[2]*100+a[1]*10+a[0];
        System.out.println(max+"-"+min+"="+(max-min));
        return max-min;
    }
}

结果:
Java趣味编程案例8----黑洞数

相关文章:

  • 2022-02-25
  • 2022-01-12
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-12-09
  • 2021-07-30
  • 2022-02-18
猜你喜欢
  • 2021-10-23
  • 2021-05-02
  • 2021-06-13
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案