📜  使用递归计算数字的设置位

📅  最后修改于: 2021-05-25 08:02:12             🧑  作者: Mango

给定数字N。任务是使用递归查找二进制表示形式的设置位数。

例子:

方法:

  1. 首先,检查号码的最低位。
  2. 如果LSB为1,则我们将答案加1,然后将数字除以2。
  3. 如果LSB为0,则将答案加0,然后将其除以2。
  4. 然后,我们递归地执行步骤(1),直到该数字大于0。

下面是上述方法的实现:

C++
// CPP program to find number 
// of set bist in a number
#include 
using namespace std;
  
// Recursive function to find 
// number of set bist in a number
int CountSetBits(int n)
{
    // Base condition
    if (n == 0)
        return 0;
          
    // If Least signifiant bit is set
    if((n & 1) == 1)
        return 1 + CountSetBits(n >> 1);
      
    // If Least significant bit is not set
    else
        return CountSetBits(n >> 1);
}
  
// Driver code
int main()
{
    int n = 21;
      
    // Function call
    cout << CountSetBits(n) << endl;
  
    return 0;
}


Java
// Java program to find number 
// of set bist in a number
class GFG
{
    // Recursive function to find 
    // number of set bist in a number
    static int CountSetBits(int n)
    {
        // Base condition
        if (n == 0)
            return 0;
              
        // If Least signifiant bit is set
        if((n & 1) == 1)
            return 1 + CountSetBits(n >> 1);
          
        // If Least significant bit is not set
        else
            return CountSetBits(n >> 1);
    }
      
    // Driver code
    public static void main (String [] args)
    {
        int n = 21;
          
        // Function call
        System.out.println(CountSetBits(n));
    }
}
  
// This code is contributed by ihritik


Python3
# Python3 program to find number 
# of set bist in a number
  
# Recursive function to find 
# number of set bist in a number
def CountSetBits(n):
      
    # Base condition
    if (n == 0):
        return 0;
          
    # If Least signifiant bit is set
    if((n & 1) == 1):
        return 1 + CountSetBits(n >> 1);
      
    # If Least signifiant bit is not set
    else:
        return CountSetBits(n >> 1);
  
# Driver code
if __name__ == '__main__':
    n = 21;
      
    # Function call
    print(CountSetBits(n));
  
# This code is contributed by 29AjayKumar


C#
// C# program to find number 
// of set bist in a number
using System;
  
class GFG
{
    // Recursive function to find 
    // number of set bist in a number
    static int CountSetBits(int n)
    {
        // Base condition
        if (n == 0)
            return 0;
              
        // If Least signifiant bit is set
        if((n & 1) == 1)
            return 1 + CountSetBits(n >> 1);
          
        // If Least significant bit is not set
        else
            return CountSetBits(n >> 1);
    }
      
    // Driver code
    public static void Main ()
    {
        int n = 21;
          
        // Function call
        Console.WriteLine(CountSetBits(n));
    }
}
  
// This code is contributed by ihritik


输出:
3