吸血鬼数字
// control/VampireNumbers.java
// TIJ4 Chapter Control, Exercise 10, page 154
/* A vampire number has an even number of digits and is formed by multiplying a
* pair of numbers containing half the number of digits of the result. The
* digits are taken from the original number in any order. Pairs of trailing
* zeroes are not allowed. Examples include: 1260 = 21 * 60, 1827 = 21 * 87,
* 2187 = 27 * 81. Write a program that finds all the 4-digit vampire numbers.
* (Suggested by Dan Forhan.)
*/
package com.controllingExecution;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.Set;
public class VampireNumbers
{
public static void main(String[] args)
{
int a1, a2, result;
int[] results = new int[14];
int i = 0;
for (a1 = 10; a1 < 100; a1++)
{
for (a2 = 10; a2 < 100; a2++)
{
result = a1 * a2;
String[] a = String.valueOf(result).split("");
String[] b = String.valueOf(a1 + "" + a2).split("");
Arrays.sort(a);
Arrays.sort(b);
if (Arrays.equals(a, b))
results[i++] = result;
}
}
Set<Integer> set = new TreeSet<Integer>();
for (int m : results)
set.add(m);
Integer[] results2 = set.toArray(new Integer[0]);
System.out.println(Arrays.toString(results2));//[1260, 1395, 1435, 1530, 1827, 2187, 6880]
}
}