|
发表于 2011-11-2 08:06:01
|
显示全部楼层
Re:*(求助)吸血鬼问题的解法
这个是取掉重复值的
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.Vector;
public class 吸血鬼 {
public static void main(String[] args){
吸血鬼 ghost =new 吸血鬼();
for(int i=1000;i<10000;i++){
ghost.是否吸血鬼(i);
}
}
public void 是否吸血鬼(int number){
final String sNumber=String.valueOf(number);
final int numberLength=sNumber.length();
if(numberLength%2!=0)return;
final ArrayList<Integer> numberArr=StringNumberToIntArray(sNumber);
final ArrayList<String> capableNumberArr=StringNumberToCapableStringArray(numberArr);
getResult(sNumber,capableNumberArr);
}
public void getResult(String sNumber,
ArrayList<String> capableNumberArr){
ArrayList<Integer> result =new ArrayList<Integer>();
int number= Integer.parseInt( sNumber);
for(int i=0;i<capableNumberArr.size();i++){
String sCapableNumber=capableNumberArr.get(i);
int heightDigit = Integer.parseInt(sCapableNumber.substring(0, sNumber.length()/2));
int lowDigit=Integer.parseInt(sCapableNumber.substring(sNumber.length()/2));
if(heightDigit * lowDigit == number){
System.out.println(number + " = " + heightDigit+" * " + lowDigit);
return ;
}
}
}
public ArrayList<Integer> StringNumberToIntArray(String args){
if(args==null)return new ArrayList<Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i=0;i<args.length();i++){
result.add(Integer.parseInt(args.substring(i,i+1)));
}
return result;
}
public ArrayList<String> StringNumberToCapableStringArray(ArrayList<Integer> args){
if(args==null)return new ArrayList<String>();
TreeSet<String> result=new TreeSet<String>();
StringNumberToCapableIntArrayRecursion(args,result,"");
return new ArrayList<String>(result);
}
public void StringNumberToCapableIntArrayRecursion(ArrayList<Integer> args,TreeSet<String> result
,String curValue){
if(args.size()<=0){
result.add(curValue);
return;
}
for(int i=0;i<args.size();i++){
ArrayList<Integer> temp=new ArrayList(args);
Integer addValue=temp.remove(i);
StringNumberToCapableIntArrayRecursion(temp,result,curValue+addValue);
}
}
} |
|