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+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告