吸血鬼数字
本人不是精通算法,闲来无事写了个求吸血鬼数字的函数,性能有点慢,希望大神批评指正给点意见,怎么修改下能把性能提升。
package com.cnroa.util; import java.util.Arrays; import java.util.List; public class Test { public static void main(String[] args){// Comparator<Object> com=Collator.getInstance(java.util.Locale.CHINA); // String[] aa = {"上海","云南","河北","湖南","西藏自治区","陕西","香港特别行政区","黑龙江"}; // Arrays.sort(aa,com); // for(String i : aa){System.out.println(i);} xugNumber(6); // rejectOne(8918); } public static List<Integer> xugNumber(Integer num){ if(num%2 != 0){ System.out.println("需要计算的不是偶位数"); return null; } Integer first = getMin(num); Integer end = getMax(num); for(int i=first;i<=end;i++){ boolean flag = rejectOne(i); if(flag) System.out.println(i); } return null; } public static Integer getMin(Integer num){ StringBuffer sb = new StringBuffer(); sb.append("1"); for(int i=0;i<num-1;i++) sb.append("0"); return Integer.parseInt(sb.toString()); } public static Integer getMax(Integer num){ StringBuffer sb = new StringBuffer(); sb.append("1"); for(int i=0;i<num;i++) sb.append("0"); return Integer.parseInt(sb.toString())-1; } public static boolean rejectOne(Integer number){ Integer half = (number+"").length()/2; Integer first = getMin(half); Integer end = getMax(half); for(int i=first;i<=end;i++){ for(int j=first;j<=end;j++){ if(i*j==number){ boolean flag = rejectThree(i+"",j+"",number+""); if(flag){ System.out.println(i+"---"+j); return true; } } } } return false; } public static boolean rejectTwo(String half,String all){ boolean flag = true; char[] temp = half.toCharArray(); for(char a : temp){ if(!all.contains(a+"")) flag = false; } for(int i=0;i<temp.length-1;i++){ for(int j=i+1;j<temp.length;j++){ if(temp[i] == temp[j]) flag = false; } } return flag; } public static boolean rejectThree(String one,String two,String all){ boolean flag = false; char[] temp1 = one.toCharArray(); int numOne = 0; for(char a : temp1){ if(all.contains(a+"")) numOne++; } int numTwo = 0; for(char a : temp1){ if(all.contains(a+"")) numTwo++; } String[] sortSource =all.split(""); String[] sortTarget =(one+two).split(""); Arrays.sort(sortSource); Arrays.sort(sortTarget); if(numOne == all.length()/2 && numTwo == all.length()/2 && arrayToString(sortSource).equals(arrayToString(sortTarget))){ flag = true; } return flag; } public static String arrayToString(String[] s){ StringBuffer sb = new StringBuffer(); for(String i : s) sb.append(i); return sb.toString(); } }