This article describes the method of calculating the number of black holes in Java. Share it for your reference, as follows:
Any 5-digit number, such as: 34256, disrupt and rearrange its digit numbers to get a maximum number: 65432 and a minimum number 23456. Find the difference between these two numbers and get: 41976. Repeat the above process with this number again (if there are less than 5 digits, add 0 in the first place). By doing this, the numbers will fall into a certain cycle (called a digital black hole).
For example, the number just now will fall into this cycle: [82962,75933, 63954, 61974].
Please write a program to find all possible loop circles with 5 digits and output, each loop circle takes up 1 line. If all the 5-digit numbers are the same, the loop circle is [0], which can be ignored. The output format of the loop circle is imitated as:
[82962,75933, 63954, 61974]
The order of numbers can be ignored.
Test.java:
public class Test {static int r=0;static int b[]=new int[16];static int c[]=new int[5];static int sort(int n,boolean boo) //Sorting function { int i,j,sum=0,temp; int a[]=new int[5]; for(i=0;i<5;i++) { a[i]=n%10; n/=10; } for(j=0;j<4;j++) for(i=0;i<4-j;i++) { if(a[i]<a[i+1]&&boo) { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; } if(a[i]>a[i+1]&&!boo) { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; } } for(i=0;i<5;i++) sum+=a[i]*(int)Math.pow(10,4-i); return sum;}static boolean Boo(int d[])//Judge function { int n,t,q,i,j; boolean flag=true; for(i=0;i<16;i++) for(j=i+1;j<16;j++) if(b[i]==b[j])//Judge whether there is a loop, you only need to judge whether the same number appears twice { d[0]=i; d[1]=j; n=ji; for(q=0;q<=r;q++) for(t=i;t<=j;t++) if(c[q]==b[t]) flag=false;//Use a one-dimensional array to store the one-digit number of the loop circle (any digit is OK, the first digit is selected here) if(flag) c[r++]=b[i];//If any bit in the newly generated loop circle is different from the value stored in the original one-dimensional array, then take the one of the loop circle to save the return flag; } return flag;} public static void main(String[] args){ int n,m,w,t,p; int r=1; boolean flag=false; int d[]=new int[2]; System.out.println("Wulin.com test result:"); for(m=10000;m<100000;m++) { n=m; for(p=0;p<16;p++) { w=sort(n,true)-sort(n,false); b[p]=w; n=w; } if(Boo(d))//Output different loop circles { System.out.printf("["); for(t=d[0];t<d[1]-1;t++) System.out.printf("%d,",b[t]); System.out.printf("%d",b[t]); System.out.printf("]/n"); } }}}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Summary of Java Mathematical Operation Skills", "Tutorials of Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.