当前位置: 代码迷 >> 综合 >> TIJ4 Chapter Control, Exercise 10, page 154
  详细解决方案

TIJ4 Chapter Control, Exercise 10, page 154

热度:50   发布时间:2024-01-17 14:35:04.0

吸血鬼数字

// 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.) */ 
首先从吸血鬼数字本身考虑,则从1000遍历到9999。这需要找出每一个数字的是否存在对应的一对因子使之满足吸血鬼数字的条件,此方法工作量大且算法难以实现;同时对于一些特殊数字(如素数等),则浪费运算时间。故此从因子方面考虑。
所求范围是4位数,所以两因子均为两位数,即范围从10~99。将两者相乘得到的结果与两者本身进行相应的对比即可得到想要的结果。比较过程中,将两因子与结果数字转换为字符串并排序,最后进行比较,即可得到比较结果。
此种算法输出的结果会有一半的数字是重复的,所以先将结果保存在整型数组中,在转换为列表消去重复项进行输出。
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]}
}
  相关解决方案