Java程序检查输入数字是否为Neon数


在本文中,我们将了解如何检查给定的输入数字是否为Neon数。一个Neon数是指其平方数的各位数字之和等于该数字本身的数。

示例场景

Input: num = 9;
Output: The given input is a neon number

如何在Java中检查Neon数?

要检查给定的输入在Java中是否为Neon数,请使用以下方法:

  • 使用for循环
  • 使用while循环
  • 使用递归

使用for循环

在这种方法中,for循环会一直迭代,直到给定输入的平方不等于0。在每次迭代中,提取最后一位数字并将其加到一起以获得平方的各位数字之和。然后,使用if-else块检查给定的输入是否为Neon数。

示例

在这个示例中,我们使用for循环来检查Neon数。

public class NeonNumbers{
   public static void main(String[] args){
      int my_input, input_square, sum = 0;
      my_input = 9;
      System.out.print("The number is: " + my_input);
      input_square = my_input*my_input;
      for (; input_square != 0; input_square /= 10) {
         sum += input_square % 10;
      }
      if(sum != my_input)
         System.out.println("\nThe given input is not a Neon number.");
      else
         System.out.println("\nThe given input is Neon number.");
   }
}

执行此代码后,将产生以下结果:

The number is: 9
The given input is Neon number.

使用while循环

这是在Java中检查Neon数的另一种方法。它使用了与上面讨论的相同的逻辑,但实现方式不同。我们使用while循环而不是for循环。

示例

在下面的示例中,我们使用while循环来检查输入数字是否为Neon数。

public class NeonNumbers{
   public static void main(String[] args){
      int my_input, input_square, sum = 0;
      my_input = 9;
      System.out.printf("The number is %d ", my_input);
      input_square = my_input*my_input;
      while(input_square < 0){
         sum = sum+input_square%10;
         input_square = input_square/10;
      }
      if(sum != my_input)
         System.out.println("\nThe given input is not a Neon number.");
      else
         System.out.println("\nThe given input is Neon number.");
   }
}

运行此代码时,它将显示以下输出:

The number is 9
The given input is Neon number.

使用递归

在递归方法中,我们创建一个函数,该函数将调用自身以检查给定的输入数字是否为Neon数。

示例

以下示例演示了如何在递归的帮助下检查给定的输入是否为Neon数。

public class NeonNumbers {
   public static int checkNeonFunc(int input_square, int sum) {
      if (input_square == 0) {
         return sum;
      } else {
         return checkNeonFunc(input_square / 10, sum + (input_square % 10));
      }
   }
   public static void main(String[] args) {
      int my_input, input_square, sum = 0;
      my_input = 9;
      System.out.println("The number is: " + my_input);
      input_square = my_input*my_input;
      if (checkNeonFunc(input_square, 0) == my_input)
         System.out.println(my_input + " is a Neon Number.");
      else
         System.out.println(my_input + " is not a Neon Number.");
   }
}

执行上述代码后,将产生以下结果:

The number is: 9
9 is a Neon Number.

更新于: 2024年8月1日

1K+ 浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.