吸血鬼数字算法

“吸血鬼数字”就是指位数为偶数的数字(我们算得是4位的),可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数字,其中从偶数位数字中选取的数字可以任意排列。以两个0截尾的数字是不允许的。例如:1260=21*60          1827=21*87          2187=27*81 
今天在Thinking in JAVA 中做到的练习题。

网上找到的比较好的算法:

 1 public class Test10 {
 2     public static void main(String[] args) {
 3         String[] ar_str1, ar_str2;
 4         int sum = 0;
 5         for (int i = 10; i < 100; i++) {
 6             for (int j = i + 1; j < 100; j++) {
 7                 int i_val = i * j;
 8                 if (i_val < 1000 || i_val > 9999)
 9                     continue; // 积小于1000或大于9999排除,继续下一轮环
10                 ar_str1 = String.valueOf(i_val).split("");
11                 ar_str2 = (String.valueOf(i) + String.valueOf(j)).split("");
12                 java.util.Arrays.sort(ar_str1);
13                 java.util.Arrays.sort(ar_str2);
14                 if (java.util.Arrays.equals(ar_str1, ar_str2)) {
15                     // 排序后比较,为真则找到一组
16                     sum++;
17                     System.out.println("第" + sum + "组: " + i + "*" + j + "="
18                             + i_val);
19                 }
20             }
21         }
22         System.out.println("共找到" + sum + "组吸血鬼数");
23     }
24 }

《Think in java》官方答案:

 1 public class VampireNumbers {    
 2         static int a(int i) {
 3             return i/1000;
 4         }
 5         static int b(int i) {
 6             return (i%1000)/100;
 7         }
 8         static int c(int i) {
 9             return ((i%1000)%100)/10;
10         }
11         static int d(int i) {
12             return ((i%1000)%100)%10;
13         }
14         static int com(int i, int j) {
15             return (i * 10) + j;
16         }
17         static void productTest (int i, int m, int n) {
18             if(m * n == i) System.out.println(i + " = " + m + " * " + n);
19         }    
20     public static void main(String[] args) {        
21         for(int i = 1001; i < 9999; i++) {            
22             productTest(i, com(a(i), b(i)), com(c(i), d(i)));
23             productTest(i, com(a(i), b(i)), com(d(i), c(i)));
24             productTest(i, com(a(i), c(i)), com(b(i), d(i)));
25             productTest(i, com(a(i), c(i)), com(d(i), b(i)));
26             productTest(i, com(a(i), d(i)), com(b(i), c(i)));
27             productTest(i, com(a(i), d(i)), com(c(i), b(i)));
28             productTest(i, com(b(i), a(i)), com(c(i), d(i)));
29             productTest(i, com(b(i), a(i)), com(d(i), c(i)));
30             productTest(i, com(b(i), c(i)), com(d(i), a(i)));
31             productTest(i, com(b(i), d(i)), com(c(i), a(i)));
32             productTest(i, com(c(i), a(i)), com(d(i), b(i)));
33             productTest(i, com(c(i), b(i)), com(d(i), a(i)));
34         }            
35     } 
36 }

 

posted @ 2013-04-19 09:49  vincent_hv  阅读(2128)  评论(0编辑  收藏  举报