每日一题——“吸血鬼”数字

193 阅读2分钟

「这是我参与2022首次更文挑战的第27天,活动详情查看:2022首次更文挑战

大家好,我是洋哥。今天给大家带来的是每日一题——“吸血鬼”数字。

题目要求

吸血鬼数字是指位数为偶数的数字,可以由一堆数字相乘而得到。而这对数字各包含乘积的一半位数的数字,其中从最初的数字中选取的数字可以任意排序。以两个0结尾的数字是不允许的,例如,下列的数字都是“吸血鬼”数字:  

1260=21*60

1827=21*87

2187=27*81  

写出一个程序,找出4位数的所有吸血鬼数字

建议用时:10-15分钟

难度:中等 

知识点考察

这道题主要考察的是数组和Java程序流程控制的综合。目前我也是刚学到数组,一些内容了解的还不够透彻,我发现这道题很有意思就发出来和大家探讨一下,仅供参考。

 

 

问题分析

第一,我们肯定要遍历1001-9999的数字,所以外层需要一个for循环。

第二,我们需要得到每一位的数字,因为吸血鬼数字就是本身数字的不同排列。

第三,我们对得到的数字的每一位进行排列组合,两两一组相乘,如果能实现"吸血鬼",那么就是"吸血鬼"数字,否则就不是。

 

 

相关知识点复习

第一个是要复习for循环的知识尤其是嵌套循环。

第二个是数组的知识,之后会详细介绍。

 

 

代码实现

public class Test1 {
public static void main(String[] args) {
  for (int num = 1001; num < 10000; num++) {
  math(num);
  }
}
 
public static void math(int num) {
      int[] temp1 = new int[2];
      int[] temp2 = new int[2];
       
      int a = num / 1000;
      int b = num / 100 % 10;
      int c = num / 10 % 10;
      int d = num % 10;
      int[] data = { a, b, c, d };
      for (int i = 0; i < data.length; i++) {
      for (int j = 0; j < data.length; j++) {
      if (i == j) {
      continue;
      }
      temp1[0] = data[i];
      temp1[1] = data[j];
      for (int m = 0; m < data.length; m++) {
      if (m != i && m != j) {
      temp2[0] = data[m];
      for (int n = 0; n < data.length; n++) {
      if (n != i && n != j && n != m) {
      temp2[1] = data[n];
      multi(data, temp1, temp2);
      }
      }
      }
      }
      }
      }
}
 
public static int toInt(int[] temp) {
  int m = 0;
  int[] temp1 = new int[temp.length];
  for (int i = 0; i < temp.length; i++) {
  temp1[i] = temp[i] * (int) Math.pow(10, temp.length - 1 - i);
  }
  for (int i = 0; i < temp1.length; i++) {
  m += temp1[i];
  }
  return m;
}
 
public static void multi(int[] temp, int[] temp1, int[] temp2) {
  int i = toInt(temp1);
  int j = toInt(temp2);
  int k = toInt(temp);
  if (k == i * j) {
  System.out.println(k + "=" + i + "*" + j);
  }
  }
}

 

 

总结和建议

这是我初学数组时觉得很有意思的一道题,目前还在探索中,还没学好,就是建议大家从这开始就要多刷题了。