吸血鬼数字—THINKING IN JAVA中一道习题


import java.util.*;

public class Test01 {
    
    public static void main(String[] args) {
               
        int num1, num2, product, count;
        int vampCount = 0;
        int[] startDigit = new int[4];  
        int[] productDigit = new int[4]; 
        for(num1 = 10; num1 <= 99; num1++){
       // num2 = num1 + 1 控制吸血鬼数值重复出现
            for(num2 = num1 + 1; num2 <= 99; num2++){
                product = num1 * num2;
                if(product < 1000)
                    continue;
                startDigit[0] = num1/10;
                startDigit[1] = num1%10;
                startDigit[2] = num2/10;
                startDigit[3] = num2%10;
                productDigit[0] = product/1000;
                productDigit[1] = (product%1000)/100;
                productDigit[2] = (product%100)/10;
                productDigit[3] = product%10;
                count = 0;
                for(int i = 0;i < 4; i++){
                    for(int j = 0; j < 4; j++){
                        if(startDigit[i] == productDigit[j]){
                            count++;
                            startDigit[i] = -1;
                            productDigit[j] = -2;
                        }
                    }
                }
                if(count == 4){
                    vampCount++;
                    System.out.println("第"+vampCount+"个吸血鬼数字为:"+product+"="+num1+"*"+num2);
                }                
            }
        }
        
        
        /* 网上找到的另一种方法,很独到
        String[] ar_str1, ar_str2;   
        int sum = 0;   
        for (int i = 10; i < 100; i++) {   
            for (int j = i + 1; j < 100; j++) {   
                int i_val = i * j;   
                if (i_val < 1000 || i_val > 9999)   
                    continue; // 积小于1000或大于9999排除,继续下一轮环   
                ar_str1 = String.valueOf(i_val).split("");   
                ar_str2 = (String.valueOf(i) + String.valueOf(j)).split("");   
                java.util.Arrays.sort(ar_str1);   
                java.util.Arrays.sort(ar_str2);   
                if (java.util.Arrays.equals(ar_str1, ar_str2)) {   
                    // 排序后比较,为真则找到一组   
                    sum++;   
                    System.out.println("第" + sum + "组: " + i + "*" + j + "="   
                            + i_val);   
                }   
            }   
        }   
        System.out.println("共找到" + sum + "组吸血鬼数");   
        
        */
        
    }
}

 

 

 

posted @ 2013-04-02 01:04  wannianma  阅读(259)  评论(0编辑  收藏  举报