Java
 Computer >> コンピューター >  >> プログラミング >> Java

再帰を使用して数値の桁の合計を見つけるJavaプログラム


この記事では、再帰を使用して数値の桁の合計を見つける方法を理解します。再帰関数は、特定の条件が満たされるまで自分自身を複数回呼び出す関数です。

再帰は、自己相似的な方法でアイテムを繰り返すプロセスです。プログラミング言語では、プログラムで同じ関数内の関数を呼び出すことができる場合、それは関数の再帰呼び出しと呼ばれます。

多くのプログラミング言語は、スタックを使用して再帰を実装します。一般に、関数(呼び出し元)が別の関数(呼び出し先)またはそれ自体を呼び出し先として呼び出すときはいつでも、呼び出し元関数は実行制御を呼び出し先に移します。この転送プロセスには、発信者から着信者に渡されるデータも含まれる場合があります。

以下は同じのデモンストレーションです-

入力

入力が-

であると仮定します
Enter the number : 12131415

出力

必要な出力は-

になります
The Sum of digits of 12131415 is 18

アルゴリズム

Step 1 - START
Step 2 - Declare two integer values namely my_input and my_result
Step 3 - Read the required values from the user/ define the values
Step 4 - A recursive function ‘digitSum’ is defined which takes an integer as input. The function computes the reminder by re-iterating over the function multiple times, until the base condition is reached.
Step 5 - The recursive function ‘digitSum’ is called and its result is assigned to ‘my_result’
Step 6 - Display the result
Step 7 - Stop

例1

ここでは、プロンプトに基づいてユーザーが入力を入力しています。この例は、コーディンググラウンドツールでライブで試すことができます 再帰を使用して数値の桁の合計を見つけるJavaプログラム

import java.util.Scanner;
public class Sum{
   public static void main(String args[]){
      int my_input, my_result;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      my_result = digitSum(my_input);
      System.out.println("The Sum of digits of " + my_input + " is " + my_result);
   }
   static int digitSum(int n){
      if (n == 0)
         return 0;
      return (n % 10 + digitSum(n / 10));
   }
}

出力

Required packages have been imported
A reader object has been defined
Enter the number : 12131415
The Sum of digits of 12131415 is 18

例2

ここでは、整数は事前に定義されており、その値にアクセスしてコンソールに表示されます。

public class Sum{
   public static void main(String args[]){
      int my_input = 12131415;
      System.out.println("The number is defined as : " +my_input);
      int my_result = digitSum(my_input);
      System.out.println("The Sum of digits of " + my_input + " is " + my_result);
   }
   static int digitSum(int n){
      if (n == 0)
         return 0;
      return (n % 10 + digitSum(n / 10));
   }
}

出力

The number is defined as : 12131415
The Sum of digits of 12131415 is 18

  1. 再帰なしで数値の桁の合計を見つけるPythonプログラム

    再帰の方法を使用せずに数値の桁の合計を見つける必要がある場合は、「%」演算子、「+」演算子、および「//」演算子を使用できます。 以下は同じのデモンストレーションです- 例 def sum_of_digits(my_num):    sum_val = 0    while (my_num != 0):       sum_val = sum_val + (my_num % 10)       my_num = my_num//10    return sum_val my

  2. Pythonで再帰を使用して数の階乗を見つける方法は?

    数値の階乗は、1からその数値までのすべての数値の積です。 関数がそれ自体を呼び出す場合、その関数は再帰関数と呼ばれます。 次のプログラムでは、factorial()関数は1つの引数を受け入れ、値が1に達するまで値を1つ減らして、それ自体を呼び出し続けます。 例 def factorial(x):     if x==1:         return 1     else:         return x*factorial(x-1) f=factorial(5) pr