📜  使用递归计算给定数字N中数字K的出现

📅  最后修改于: 2021-05-06 23:46:50             🧑  作者: Mango

给定一个大于0的整数N ,任务是查找出现在给定数字N中的数字K。

例子:

方法:想法是在每个步骤中使用递归来提取数字的最低有效位,并检查提取的数字是否等于给定的数字K。最后,通过计算该数字除以10的整数除法,递归检查该数字的下几个数字。

下面是上述方法的实现:

C++
// C++ implementation to count 
// the occurrence of a digit in 
// number using Recursion
  
#include 
  
using namespace std;
  
// Function to count the digit K
// in the given number N
int countdigits(int n, int k)
{
    if (n == 0)
        return 0;
  
    // Extracting least 
    // significant digit
    int digit = n % 10;
    if (digit == k)
        return 1 + countdigits(n / 10, k);
  
    return countdigits(n / 10, k);
}
  
// Driver Code
int main()
{
    int n = 1000;
    int k = 0;
  
    cout << countdigits(n, k) << endl;
    return 0;
}


Java
// Java implementation to count 
// the occurrence of a digit in 
// number using Recursion
  
import java.util.*;
   
class GFG {
      
    // Function to count the digit K
    // in the given number N
    static double countdigits(int n, int k)
    {
        if (n == 0)
            return 0;
   
        // Extracting least 
        // significant digit
        int digit = n % 10;
        if (digit == k)
            return 1 + countdigits(n / 10, k);
   
        return countdigits(n / 10, k);
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        int n = 1000;
        int k = 0;
        System.out.println(countdigits(n, k));
    }
}


Python3
# Python implementation to count 
# the occurrence of a digit in 
# number using Recursion
  
# Function to count the digit K
# in the given number N
def countdigits(n, k):
    if n == 0:
        return 0
           
    # Extracting least 
    # significant digit
    digit = n % 10
       
    if digit == k:
        return 1 + countdigits(n / 10, k)
   
    return countdigits(n / 10, k)
  
# Driver Code
if __name__ == "__main__":
    n = 1000;
    k = 0;
    print(countdigits(n, k))


C#
// C# implementation to count 
// the occurrence of a digit in 
// number using Recursion
  
using System;
   
class GFG {
      
    // Function to count the digit K
    // in the given number N
    static double countdigits(int n, 
                              int k)
    {
        if (n == 0)
            return 0;
   
        // Extracting least 
        // significant digit
        int digit = n % 10;
        if (digit == k)
            return 1 + 
             countdigits(n / 10, k);
   
        return countdigits(n / 10, k);
    }
   
    // Driver Code
    static public void Main()
    {
        int n = 1000;
        int k = 0;
        Console.WriteLine(countdigits(n, k));
    }
}


输出:
3