Java algorithm digital black hole

Question description

For any four-digit number, as long as the numbers in each digit are not exactly the same, there is this rule:
  1) Combine the four numbers that make up the four-digit number Arrange from large to small to form the largest four-digit number composed of these four numbers;
  2) Arrange the four numbers that make up the four-digit number from small to large to form the largest four-digit number composed of these four numbers. The smallest four-digit number composed of four numbers (if the four numbers contain 0, the number obtained is less than four digits);
  3) Find the difference between the two numbers and get a new Four digits (high-order zeros are reserved).
  Repeat the above process, and the final result you will get is 6174.
  For example: 4312 3087 8352 6174, after three transformations, we get 6174

Input
Input description:
  A four-digit integer, input to ensure that the four digits are not exactly the same
Input sample Example:
4312

output

Output description:
  An integer indicating how many times this number can be transformed to get 6174
Output sample:
3

HINT: Time limit: 1.0s Memory limit: 256.0MB

Problem-solving ideas

First get the number in each bit, then sort and subtract the maximum and minimum values, and then loop until it equals 6417.

code

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner=new Scanner(System.in);
        int m=scanner.nextInt();           //输入数字m
        int n=0;                            //记录变化的次数
        while (m!=6174){
    
                        //判断是否等于6147
                int m1=m/1000;              //得到千位
                int m2=m/100%10;            //得到百位
                int m3=m/10%10;             //得到十位
                int m4=m%10;                //得到个位
                int []a={
    
    m1,m2,m3,m4};      //加入数组
                Arrays.sort(a);             //从小到大排序
                int n2=a[3]*1000+a[2]*100+a[1]*10+a[0];//降序
                int n1=a[0]*1000+a[1]*100+a[2]*10+a[3];//升序
                m= n2-n1;                   //相减变换
                n++;                        //变化次数加1
        }
        System.out.println(n);              //输出变化次数
    }
}

おすすめ

転載: blog.csdn.net/joreng/article/details/123680559