Posted on 2012-05-15 09:53
timelyxyz 閱讀(138)
評論(0) 編輯 收藏
題目:吸血鬼數字是指位數為偶數的數字,可以由一對數字相乘而得到,而對數字各包含乘積的一半數的數字,其中從最初的數字中選取的數字可以任意排序。以兩個0結尾的數字是不允許的,列如:
1260=21*60;
1827=21*87;
2187=27*81;
請寫出一個程序,找出所有的4位吸血鬼數字。
解:反過來想,不從考慮某個數(1001到9999)是不是吸血鬼數,而是遍歷2位數相乘,看是否符合某種規則,符合的話,他們的積就是吸血鬼數
package test1;
import java.util.Arrays;
import java.util.Scanner;
/**
* 吸血鬼數字:位數為偶數,可以由一對數字相乘而得,這對數字分別是吸血鬼數字的一半位數的,順序不規定<br>
* 1260=12*60, 1827=21*87
*/
public class Vampire {
public static void main(String[] args) {
System.out.printf("Please enter the length of the num : ");
Scanner s = new Scanner(System.in);
int x = s.nextInt();
calVampire(x);
}
public static void calVampire(int n) {
if (n % 2 != 0)
return;
else {
int subLength = n / 2;
int total = 0;
int min = (int) Math.pow(10, subLength - 1);
int max = (int) Math.pow(10, subLength) - 1;
for (int p = min; p <= max; p++) {
for (int k = p + 1; k <= max; k++) {
int val = p * k;
if (val > 9999 || val < 1000)
continue;
String[] s1 = String.valueOf(val).split("");
String[] s2 = (String.valueOf(p) + String.valueOf(k))
.split("");
Arrays.sort(s1);
Arrays.sort(s2);
if (Arrays.equals(s1, s2)) {
total++;
System.out.println(p + " * " + k + "=" + val);
}
}
}
System.out.println("Total num is : " + total);
}
}
}