值得纪念的一次编程

楼主有点小白,个人觉得值得纪念,不喜勿喷。

最近在看java编程思想,遇到了求吸血鬼数的那一题,自己做的时候是把四位数分别放到数组arr里面,然后建立两个数组分别存arr中的两位。之后就遇到了许多问题,比如:如何将已经放入a数组的数不放入b数组,如何遍历数组使numa和numb不会重复计算等。其中将已经放入a数组的数不放入b数组总感觉遍历arr会导致循环太多。始终想不出来,然后看答案了。

答案是这样子的。

public static void main(String[] args) {
    int[] startDigit = new int[4];
    int[] productDigit = new int[4];
    for(int num1 = 10; num1 <= 99; num1++)
        for(int num2 = num1; num2 <= 99; num2++) {
        // Pete Hartley's theoretical result:
        // If x•y is a vampire number then
        // x•y == x+y (mod 9)
        if((num1 * num2) % 9 != (num1 + num2) % 9)
            continue;
        int product = num1 * num2;
        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 % 1000 % 100 / 10;
        productDigit[3] = product % 1000 % 100 % 10;
        int count = 0;
        for(int x = 0; x < 4; x++)
            for(int y = 0; y < 4; y++) {
                if(productDigit[x] == startDigit[y]) {
                    count++;
                    productDigit[x] = -1;
                    startDigit[y] = -2;
                    if(count == 4)
                        Controlling Execution 47
                        System.out.println(num1 + " * " + num2
                        + " : " + product);
                    }
            }
        }
}
                    

答案是一个数字一个数字地比对的,而我自己的思想是整体比对的,思想上的差距吧。这一题的答案给了我不少惊喜,感觉自己的思想还是太不广阔了。嗯,值得纪念!

posted @ 2016-05-20 18:04  海那边天尽头  阅读(191)  评论(0编辑  收藏  举报