目录
1.什么是6174数字黑洞
把一个四位数的四个数字由小至大排列,组成一个新数,又由大至小排列排列组成一个新数,这两个数相减,之后重复这个步骤,只要四位数的四个数字不重复,数字最终便会变成 6174;
2.验证6174
废话不多说,直接上代码
public class Test6174 {
static int flag = 0;
static Random random = new Random();
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> r = new ArrayList<Integer>();
for(int i=0;i<4;i++) {
getNum(r);
}
System.out.println("原始数字:"+r);
flag = 0;
get6174(r);
}
private static int get6174(List<Integer> r) {
sortMinList(r);
int minNum = getNumber(r);
System.out.println("小:"+minNum);
sortMaxList(r);
int maxNum = getNumber(r);
System.out.println("大:"+maxNum);
int nn = maxNum-minNum;
System.out.println("maxNum-minNum="+nn);
flag++;
if(nn == 6174) {
System.out.println(flag+"次,正确:"+nn);
}else {
System.out.println("不正确:"+nn);
r = getNumberList(nn);
get6174(r);
}
return 0;
}
private static List<Integer> getNumberList(int r) {
List<Integer> res = new ArrayList<Integer>();
res.add(r/1000);
r = r%1000;
res.add(r/100);
r = r%100;
res.add(r/10);
r = r%10;
res.add(r);
return res;
}
private static int getNumber(List<Integer> r) {
int res = 0;
res += (r.get(0)*1000);
res += (r.get(1)*100);
res += (r.get(2)*10);
res += (r.get(3)*1);
return res;
}
private static void sortMinList(List<Integer> r) {
r.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
}
private static void sortMaxList(List<Integer> r) {
r.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
}
private static int getNum(List<Integer> r) {
int red = random.nextInt(9);
if(r.contains(red)) {
red = getNum(r);
}else {
r.add(red);
}
return red;
}
}
3.总结
编程的乐趣在于发现