吸血鬼数字(java)

今天在学习《Thinking in java》在时候看到一个习题是关于吸血鬼的,由于太久没有写这方面的代码决定试一下手,还有有一点意思 的,还查了一点百度。

先说一下吸血鬼数是什么,吸血鬼数字是指位数为偶数的数字,可以由一对数字相乘而得到,而这对数字包含乘积的一半位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的。---摘自《Thinking in java》;

先贴我的第一次尝试代码:一看就非常麻烦

public class ForTest {
public static void main(String[] args) {
int x , y ,z ;
for(x = 1000; x<9999;x ++ ) {
if(x %100 == 0) {
continue;
}
for(y =10;y<100;y++) {
for(z =10; z<100; z++) {
if(y*z == x ) {
                                         int a = x/1000%10;
int b = x/100%10;
int c = x/10%10;
int d = x%10;                 //将x的每位的数字拆分出来
int e = y/10%10;            //将y的每位拆分
int f = y%10;        
int g = z/10%10;            //将z的每位拆分
int h = z%10;
ArrayList<Integer> i = new ArrayList<>();
ArrayList<Integer> j = new ArrayList<>();
i.add(a);i.add(b);
i.add(c);i.add(d);
j.add(e);j.add(f);j.add(g);j.add(h);    //分别放入list集合中
Collections.sort(i);                            //用集合的工具类将这两个集合排序
Collections.sort(j);
if(i.toString().equals(j.toString())){
    System.out.println(x+"," + y +"," +z);
    y=100;                    //为防止y*z=x和z*y=x   直接设置y=99,跳出y循环
}
}
}
}
}
}

}

总结了一波,发现这样的代码太麻烦了,如果位数再多一点。。。。

所以我查资料研究了第二种写法

public class ForTest {
public static void main(String[] args) {
int x , y ,z ;
for(x = 1000; x<9999;x ++ ) {
if(x %100 == 0) {
continue;
}
for(y =10;y<100;y++) {
for(z =10; z<100; z++) {
if(y*z == x ) {
     String[] a = String.valueOf(x).split("");           //将x拆分成String数组
               String[] b = String.valueOf(y+""+z).split(""); //将y+z 拆分成String[],注意拼接时的""要放中间
Arrays.sort(a);                                    //这次用数据的工具排序,
Arrays.sort(b);
if(Arrays.equals(a, b)){

System.out.println(x+"," + y +"," +z);

                                                         y=100;     //同样为防止重复而跳出

}
}
}
}
}
}

}

总结一波,有很多工具类都是现成写好的,我们要灵活运用。做到快速有效的编程而且阅读性更强的代码才是我们的目的;

猜你喜欢

转载自blog.csdn.net/sosozha/article/details/80637280