日期:2014-05-20  浏览次数:20799 次

吸血鬼数字-笨办法—求优化!
Java code

public class VampireNum {
    public static void main(String[] args) {
        int i, a, b, c, d;
        for (i = 1111; i <= 9999; i++) {
            if (i % 100 != 0) {
                a = i / 1000;
                b = i / 100 % 10;
                c = i / 10 % 10;
                d = i % 10;
                if ((a > 0 && c > 0) && (a * 10 + b) * (c * 10 + d) == i
                        || (a * 10 + d) * (c * 10 + b) == i) {
                    System.out.println(i);
                }
                if ((a > 0 && b > 0) && (a * 10 + c) * (b * 10 + d) == i
                        || (a * 10 + d) * (b * 10 + c) == i) {
                    System.out.println(i);
                }
                if ((a > 0 && d > 0) && (a * 10 + b) * (d * 10 + c) == i
                        || (a * 10 + c) * (d * 10 + a) == i) {
                    System.out.println(i);
                }
                if ((b > 0 && c > 0) && (b * 10 + a) * (c * 10 + d) == i
                        || (b * 10 + d) * (c * 10 + a) == i) {
                    System.out.println(i);
                }
                if ((b > 0 && d > 0) && (b * 10 + a) * (d * 10 + c) == i
                        || (b * 10 + c) * (d * 10 + a) == i) {
                    System.out.println(i);
                }
                if ((c > 0 && d > 0) && (d * 10 + b) * (c * 10 + a) == i
                        || (d * 10 + a) * (c * 10 + b) == i) {
                    System.out.println(i);
                }
            }
        }

    }
}


结果:
1260
1395
1435
1530
1827
2187
6880
求优化!

------解决方案--------------------
Java code
    for (int x = 10; x <= 99; x++) {
      int z;
      outer: for (int y = Math.max(x, 1000 / x); y <= 99 && (z = x * y) <= 9999; y++) {
        if (z < 1000) {
          continue;
        }
        int[] count1 = new int[10];
        int[] count2 = new int[10];
        count1[z / 1000]++;
        count1[z % 1000 / 100]++;
        count1[z % 100 / 10]++;
        count1[z % 10]++;
        count2[x/10]++;
        count2[x%10]++;
        count2[y/10]++;
        count2[y%10]++;
        for (int i = 0; i < count1.length; i++) {
          if (count1[i] != count2[i]) {
            continue outer;
          }
        }
        System.out.printf("%d * %d = %d%n", x, y, z);
      }
    }