📜  计算从 L 到 R 范围内所有数字的总设置位

📅  最后修改于: 2021-10-27 03:21:59             🧑  作者: Mango

给定两个正整数LR ,任务是计算从LR的所有数字的二进制表示中设置位的总数。

例子:

方法1 -原始的方法:我们的想法是从运行左至右一个循环,并从L-总结一套位的计数中所有数字R上

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count set bits in x
unsigned int
countSetBitsUtil(unsigned int x)
{
    // Base Case
    if (x <= 0)
        return 0;
 
    // Recursive Call
    return ((x % 2 == 0 ? 0 : 1)
            + countSetBitsUtil(x / 2));
}
 
// Function that returns count of set bits
// present in all numbers from 1 to N
unsigned int countSetBits(unsigned int L,
                          unsigned int R)
{
    // Initialize the result
    int bitCount = 0;
 
    for (int i = L; i <= R; i++) {
        bitCount += countSetBitsUtil(i);
    }
 
    // Return the setbit count
    return bitCount;
}
 
// Driver Code
int main()
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    printf("Total set bit count is %d",
           countSetBits(L, R));
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to count set bits in x
static int countSetBitsUtil(int x)
{
    // Base Case
    if (x <= 0)
        return 0;
 
    // Recursive Call
    return ((x % 2 == 0 ? 0 : 1) +
             countSetBitsUtil(x / 2));
}
 
// Function that returns count of set bits
// present in all numbers from 1 to N
static int countSetBits(int L, int R)
{
    // Initialize the result
    int bitCount = 0;
 
    for (int i = L; i <= R; i++)
    {
        bitCount += countSetBitsUtil(i);
    }
 
    // Return the setbit count
    return bitCount;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.printf("Total set bit count is %d",
                                 countSetBits(L, R));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function to count set bits in x
def countSetBitsUtil(x):
   
    # Base Case
    if (x < 1):
        return 0;
 
    # Recursive Call
    if (x % 2 == 0):
        return 0;
    else:
        return 1 + (countSetBitsUtil(x / 2));
 
# Function that returns count of set bits
# present in all numbers from 1 to N
def countSetBits(L, R):
   
    # Initialize the result
    bitCount = 0;
 
    for i in range(L, R + 1):
        bitCount += countSetBitsUtil(i);
 
    # Return the setbit count
    return bitCount;
 
# Driver Code
if __name__ == '__main__':
   
    # Given L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is ",
                countSetBits(L, R));
 
# This code is contributed by Princi Singh


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to count set bits in x
static int countSetBitsUtil(int x)
{
    // Base Case
    if (x <= 0)
        return 0;
 
    // Recursive Call
    return ((x % 2 == 0 ? 0 : 1) +
             countSetBitsUtil(x / 2));
}
 
// Function that returns count of set bits
// present in all numbers from 1 to N
static int countSetBits(int L, int R)
{
    // Initialize the result
    int bitCount = 0;
 
    for (int i = L; i <= R; i++)
    {
        bitCount += countSetBitsUtil(i);
    }
 
    // Return the setbit count
    return bitCount;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set bit count is {0}",
                           countSetBits(L, R));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function that counts the set bits
// from 0 to N
int countSetBit(int n)
{
    int i = 0;
 
    // To store sum of set bits from 0 - N
    int ans = 0;
 
    // Until n >= to 2^i
    while ((1 << i) <= n) {
 
        // This k will get flipped after
        // 2^i iterations
        bool k = 0;
 
        // Change is iterator from 2^i to 1
        int change = 1 << i;
 
        // This will loop from 0 to n for
        // every bit position
        for (int j = 0; j <= n; j++) {
 
            ans += k;
 
            if (change == 1) {
 
                // When change = 1 flip the bit
                k = !k;
 
                // Again set change to 2^i
                change = 1 << i;
            }
            else {
                change--;
            }
        }
 
        // Increment the position
        i++;
    }
 
    return ans;
}
 
// Function that counts the set bit
// in the range (L, R)
int countSetBits(int L, int R)
{
 
    // Return the count
    return abs(countSetBit(R)
               - countSetBit(L - 1));
}
 
// Driver Code
int main()
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set bit count is "
         << countSetBits(L, R) << endl;
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function that counts the set bits
// from 0 to N
static int countSetBit(int n)
{
    int i = 0;
 
    // To store sum of set bits from 0 - N
    int ans = 0;
 
    // Until n >= to 2^i
    while ((1 << i) <= n)
    {
 
        // This k will get flipped after
        // 2^i iterations
        boolean k = true;
 
        // Change is iterator from 2^i to 1
        int change = 1 << i;
 
        // This will loop from 0 to n for
        // every bit position
        for (int j = 0; j <= n; j++)
        {
            ans += k==true?0:1;
 
            if (change == 1)
            {
 
                // When change = 1 flip the bit
                k = !k;
 
                // Again set change to 2^i
                change = 1 << i;
            }
            else
            {
                change--;
            }
        }
 
        // Increment the position
        i++;
    }
 
    return ans;
}
 
// Function that counts the set bit
// in the range (L, R)
static int countSetBits(int L, int R)
{
 
    // Return the count
    return Math.abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.print("Total set bit count is " +
                      countSetBits(L, R) +"\n");
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
 
# Function that counts the set bits
# from 0 to N
def countSetBit(n):
    i = 0;
 
    # To store sum of set bits from 0 - N
    ans = 0;
 
    # Until n >= to 2^i
    while ((1 << i) <= n):
 
        # This k will get flipped after
        # 2^i iterations
        k = True;
 
        # Change is iterator from 2^i to 1
        change = 1 << i;
 
        # This will loop from 0 to n for
        # every bit position
        for j in range(n+1):
            ans += 0 if k == True else 1;
 
            if (change == 1):
 
                # When change = 1 flip the bit
                k = False if k == True else True;
 
                # Again set change to 2^i
                change = 1 << i;
            else:
                change -=1;
 
        # Increment the position
        i += 1;
 
    return ans;
 
# Function that counts the set bit
# in the range (L, R)
def countSetBits(L, R):
   
    # Return the count
    return abs(countSetBit(R) -
               countSetBit(L - 1));
 
# Driver Code
if __name__ == '__main__':
   
    # Given L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is ", 
          countSetBits(L, R));
 
# This code is contributed by Rajput-Ji


C#
// C# program for the above approach
using System;
class GFG{
 
// Function that counts the set bits
// from 0 to N
static int countSetBit(int n)
{
    int i = 0;
 
    // To store sum of set bits from 0 - N
    int ans = 0;
 
    // Until n >= to 2^i
    while ((1 << i) <= n)
    {
 
        // This k will get flipped after
        // 2^i iterations
        bool k = true;
 
        // Change is iterator from 2^i to 1
        int change = 1 << i;
 
        // This will loop from 0 to n for
        // every bit position
        for (int j = 0; j <= n; j++)
        {
            ans += k==true?0:1;
 
            if (change == 1)
            {
 
                // When change = 1 flip the bit
                k = !k;
 
                // Again set change to 2^i
                change = 1 << i;
            }
            else
            {
                change--;
            }
        }
 
        // Increment the position
        i++;
    }
 
    return ans;
}
 
// Function that counts the set bit
// in the range (L, R)
static int countSetBits(int L, int R)
{
 
    // Return the count
    return Math.Abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set bit count is " +
                   countSetBits(L, R) +"\n");
}
}
 
// This code is contributed by Rajput-Ji


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
unsigned int countSetBit(unsigned int n);
 
// Returns position of leftmost set bit
// The rightmost position is taken as 0
unsigned int getLeftmostBit(int n)
{
    int m = 0;
    while (n > 1) {
        n = n >> 1;
        m++;
    }
    return m;
}
 
// Function that gives the position of
// previous leftmost set bit in n
unsigned int getNextLeftmostBit(int n, int m)
{
    unsigned int temp = 1 << m;
    while (n < temp) {
        temp = temp >> 1;
        m--;
    }
    return m;
}
 
// Function to count the set bits between
// the two numbers N and M
unsigned int _countSetBit(unsigned int n,
                          int m)
{
    // Base Case
    if (n == 0)
        return 0;
 
    // Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1
    if (n == ((unsigned int)1 << (m + 1)) - 1)
        return (unsigned int)(m + 1) * (1 << m);
 
    // Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1)
            + countSetBit(n)
            + m * (1 << (m - 1)));
}
 
// Function that returns count of set
// bits present in all numbers from 1 to n
unsigned int countSetBit(unsigned int n)
{
    // Get the position of leftmost set
    // bit in n
    int m = getLeftmostBit(n);
 
    // Use the position
    return _countSetBit(n, m);
}
 
// Function that counts the set bits
// between L and R
int countSetBits(int L, int R)
{
    return abs(countSetBit(R)
               - countSetBit(L - 1));
}
 
// Driver Code
int main()
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set bit count is "
         << countSetBits(L, R);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Returns position of leftmost set bit
// The rightmost position is taken as 0
static  int getLeftmostBit(int n)
{
    int m = 0;
    while (n > 1)
    {
        n = n >> 1;
        m++;
    }
    return m;
}
 
// Function that gives the position of
// previous leftmost set bit in n
static  int getNextLeftmostBit(int n, int m)
{
     int temp = 1 << m;
    while (n < temp)
    {
        temp = temp >> 1;
        m--;
    }
    return m;
}
 
// Function that returns count of set
// bits present in all numbers from 1 to n
static int countSetBit( int n)
{
   // Get the position of leftmost set
   // bit in n
   int m = getLeftmostBit(n);
 
   // Use the position
   return _countSetBit(n, m);
}
 
// Function to count the set bits between
// the two numbers N and M
static int _countSetBit(int n, int m)
{
    // Base Case
    if (n == 0)
        return 0;
     
    // Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1
    if (n == (( int)1 << (m + 1)) - 1)
        return ( int)(m + 1) * (1 << m);
 
    // Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1) +
            countSetBit(n) +
            m * (1 << (m - 1)));
}
 
// Function that counts the set bits
// between L and R
static int countSetBits(int L, int R)
{
    return Math.abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.print("Total set bit count is " +
                             countSetBits(L, R));
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python program for the above approach
 
 
# Returns position of leftmost set bit
# The rightmost position is taken as 0
def getLeftmostBit(n):
    m = 0;
    while (n > 1):
        n = n >> 1;
        m += 1;
 
    return m;
 
 
# Function that gives the position of
# previous leftmost set bit in n
def getNextLeftmostBit(n, m):
    temp = 1 << m;
    while (n < temp):
        temp = temp >> 1;
        m -=1;
 
    return m;
 
 
# Function that returns count of set
# bits present in all numbers from 1 to n
def countSetBit(n):
    # Get the position of leftmost set
    # bit in n
    m = getLeftmostBit(n);
 
    # Use the position
    return _countSetBit(n, m);
 
 
# Function to count the set bits between
# the two numbers N and M
def _countSetBit(n, m):
    # Base Case
    if (n == 0):
        return 0;
 
    # Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    # If n is of the form 2^x-1
    if (n == int(1 << (m + 1)) - 1):
        return int(m + 1) * (1 << m);
 
 
    # Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1) + countSetBit(n) + m * (1 << (m - 1)));
 
 
# Function that counts the set bits
# between L and R
def countSetBits(L, R):
    return abs(countSetBit(R) - countSetBit(L - 1));
 
 
# Driver Code
if __name__ == '__main__':
    # Given L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is " , countSetBits(L, R));
 
# This code contributed by shikhasingrajput


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Returns position of leftmost set bit
// The rightmost position is taken as 0
static int getLeftmostBit(int n)
{
    int m = 0;
    while (n > 1)
    {
        n = n >> 1;
        m++;
    }
    return m;
}
 
// Function that gives the position of
// previous leftmost set bit in n
static int getNextLeftmostBit(int n, int m)
{
    int temp = 1 << m;
    while (n < temp)
    {
        temp = temp >> 1;
        m--;
    }
    return m;
}
 
// Function that returns count of set
// bits present in all numbers from 1 to n
static int countSetBit(int n)
{
     
    // Get the position of leftmost set
    // bit in n
    int m = getLeftmostBit(n);
     
    // Use the position
    return _countSetBit(n, m);
}
 
// Function to count the set bits between
// the two numbers N and M
static int _countSetBit(int n, int m)
{
     
    // Base Case
    if (n == 0)
        return 0;
     
    // Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1
    if (n == (( int)1 << (m + 1)) - 1)
        return ( int)(m + 1) * (1 << m);
 
    // Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1) +
            countSetBit(n) +
            m * (1 << (m - 1)));
}
 
// Function that counts the set bits
// between L and R
static int countSetBits(int L, int R)
{
    return Math.Abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given L and R
    int L = 3, R = 5;
 
    // Function call
    Console.Write("Total set bit count is " +
                          countSetBits(L, R));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count set bit in range
int countSetBits(int L, int R)
{
    // Count variable
    int count = 0;
 
    for (int i = L; i <= R; i++) {
 
        // Find the set bit in Nth number
        int n = i;
        while (n > 0) {
 
            // If last bit is set
            count += (n & 1);
 
            // Left sift by one bit
            n = n >> 1;
        }
    }
 
    // Return count
    return count;
}
 
// Driver Code
int main()
{
    // Given Range L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set Bit count is "
         << countSetBits(L, R);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
   
// Function to count set bit in range
static int countSetBits(int L, int R)
{
    // Count variable
    int count = 0;
  
    for (int i = L; i <= R; i++)
    {
  
        // Find the set bit in Nth number
        int n = i;
        while (n > 0)
        {
  
            // If last bit is set
            count += (n & 1);
  
            // Left sift by one bit
            n = n >> 1;
        }
    }
  
    // Return count
    return count;
}
  
// Driver Code
public static void main(String[] args)
{
    // Given Range L and R
    int L = 3, R = 5;
  
    // Function Call
    System.out.print("Total set Bit count is " +
                             countSetBits(L, R));
}
}
 
// This code is contributed by Ritik Bansal


Python3
# Python3 program for the above approach
 
# Function to count set bit in range
def countSetBits(L, R):
     
    # Count variable
    count = 0;
 
    for i in range(L, R + 1):
 
        # Find the set bit in Nth number
        n = i;
        while (n > 0):
 
            # If last bit is set
            count += (n & 1);
 
            # Left sift by one bit
            n = n >> 1;
 
    # Return count
    return count;
 
# Driver Code
if __name__ == '__main__':
     
    # Given range L and R
    L = 3; R = 5;
 
    # Function call
    print("Total set Bit count is ",
           countSetBits(L, R));
     
# This code is contributed by Amit Katiyar


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to count set bit in range
static int countSetBits(int L, int R)
{
     
    // Count Variable
    int count = 0;
 
    for(int i = L; i <= R; i++)
    {
         
        // Find the set bit in Nth number
        int n = i;
         
        while (n > 0)
        {
             
            // If last bit is set
            count += (n & 1);
 
            // Left sift by one bit
            n = n >> 1;
        }
    }
 
    // Return count
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given Range L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set Bit count is " +
                   countSetBits(L, R));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count set bit in [L, R]
int countSetBits(int L, int R)
{
    // Variable for count set
    // bit in range
    int count = 0;
 
    // Count set bit for all
    // number in range
    for (int i = L; i <= R; i++) {
 
        // Use inbuilt function
        count += __builtin_popcount(i);
    }
 
    return count;
}
 
// Driver Code
int main()
{
    // Given range L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set bit count is "
         << countSetBits(L, R);
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to count set bit in [L, R]
static int countSetBits(int L, int R)
{
    // Variable for count set
    // bit in range
    int count = 0;
 
    // Count set bit for all
    // number in range
    for (int i = L; i <= R; i++)
    {
 
        // Use inbuilt function
        count += Integer.bitCount(i);
    }
 
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given range L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.print("Total set bit count is " +
                            countSetBits(L, R));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function to count set bit in [L, R]
def countSetBits(L, R):
   
    # Variable for count set
    # bit in range
    count = 0;
 
    # Count set bit for all
    # number in range
    for i in range(L, R + 1):
       
        # Use inbuilt function
        count += countSetBit(i);
 
    return count;
 
def  countSetBit(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count
   
# Driver Code
if __name__ == '__main__':
   
    # Given range L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is " ,
          countSetBits(L, R));
 
# This code is contributed by sapnasingh4991


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to count set bit in [L, R]
static int countSetBits(int L, int R)
{
    // Variable for count set
    // bit in range
    int count = 0;
 
    // Count set bit for all
    // number in range
    for (int i = L; i <= R; i++)
    {
 
        // Use inbuilt function
        count += countSetBits(i);
    }
 
    return count;
}
static int countSetBits(long x)
{
    int setBits = 0;
    while (x != 0)
    {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
// Driver Code
public static void Main(String[] args)
{
    // Given range L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set bit count is " +
                         countSetBits(L, R));
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:
Total set bit count is 5

时间复杂度: O(N*Log N)
辅助空间: O(1)

方法 2 – 更好的方法:想法是从最右侧距离i处观察位,然后位在垂直序列中的2 i位置后反转。

例子:

L = 3, R = 5
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101

观察最右边的位 (i = 0) 之后的位被翻转 ( 2 0 = 1)
观察第三个最右边的位 (i = 2),这些位在 ( 2 2 = 4) 之后被翻转。
因此,我们可以以垂直方式计算位,以便在第 i 个最右边位置的位将在2 i次迭代后翻转。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function that counts the set bits
// from 0 to N
int countSetBit(int n)
{
    int i = 0;
 
    // To store sum of set bits from 0 - N
    int ans = 0;
 
    // Until n >= to 2^i
    while ((1 << i) <= n) {
 
        // This k will get flipped after
        // 2^i iterations
        bool k = 0;
 
        // Change is iterator from 2^i to 1
        int change = 1 << i;
 
        // This will loop from 0 to n for
        // every bit position
        for (int j = 0; j <= n; j++) {
 
            ans += k;
 
            if (change == 1) {
 
                // When change = 1 flip the bit
                k = !k;
 
                // Again set change to 2^i
                change = 1 << i;
            }
            else {
                change--;
            }
        }
 
        // Increment the position
        i++;
    }
 
    return ans;
}
 
// Function that counts the set bit
// in the range (L, R)
int countSetBits(int L, int R)
{
 
    // Return the count
    return abs(countSetBit(R)
               - countSetBit(L - 1));
}
 
// Driver Code
int main()
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set bit count is "
         << countSetBits(L, R) << endl;
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
// Function that counts the set bits
// from 0 to N
static int countSetBit(int n)
{
    int i = 0;
 
    // To store sum of set bits from 0 - N
    int ans = 0;
 
    // Until n >= to 2^i
    while ((1 << i) <= n)
    {
 
        // This k will get flipped after
        // 2^i iterations
        boolean k = true;
 
        // Change is iterator from 2^i to 1
        int change = 1 << i;
 
        // This will loop from 0 to n for
        // every bit position
        for (int j = 0; j <= n; j++)
        {
            ans += k==true?0:1;
 
            if (change == 1)
            {
 
                // When change = 1 flip the bit
                k = !k;
 
                // Again set change to 2^i
                change = 1 << i;
            }
            else
            {
                change--;
            }
        }
 
        // Increment the position
        i++;
    }
 
    return ans;
}
 
// Function that counts the set bit
// in the range (L, R)
static int countSetBits(int L, int R)
{
 
    // Return the count
    return Math.abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.print("Total set bit count is " +
                      countSetBits(L, R) +"\n");
}
}
 
// This code is contributed by gauravrajput1

蟒蛇3

# Python3 program for the above approach
 
# Function that counts the set bits
# from 0 to N
def countSetBit(n):
    i = 0;
 
    # To store sum of set bits from 0 - N
    ans = 0;
 
    # Until n >= to 2^i
    while ((1 << i) <= n):
 
        # This k will get flipped after
        # 2^i iterations
        k = True;
 
        # Change is iterator from 2^i to 1
        change = 1 << i;
 
        # This will loop from 0 to n for
        # every bit position
        for j in range(n+1):
            ans += 0 if k == True else 1;
 
            if (change == 1):
 
                # When change = 1 flip the bit
                k = False if k == True else True;
 
                # Again set change to 2^i
                change = 1 << i;
            else:
                change -=1;
 
        # Increment the position
        i += 1;
 
    return ans;
 
# Function that counts the set bit
# in the range (L, R)
def countSetBits(L, R):
   
    # Return the count
    return abs(countSetBit(R) -
               countSetBit(L - 1));
 
# Driver Code
if __name__ == '__main__':
   
    # Given L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is ", 
          countSetBits(L, R));
 
# This code is contributed by Rajput-Ji

C#

// C# program for the above approach
using System;
class GFG{
 
// Function that counts the set bits
// from 0 to N
static int countSetBit(int n)
{
    int i = 0;
 
    // To store sum of set bits from 0 - N
    int ans = 0;
 
    // Until n >= to 2^i
    while ((1 << i) <= n)
    {
 
        // This k will get flipped after
        // 2^i iterations
        bool k = true;
 
        // Change is iterator from 2^i to 1
        int change = 1 << i;
 
        // This will loop from 0 to n for
        // every bit position
        for (int j = 0; j <= n; j++)
        {
            ans += k==true?0:1;
 
            if (change == 1)
            {
 
                // When change = 1 flip the bit
                k = !k;
 
                // Again set change to 2^i
                change = 1 << i;
            }
            else
            {
                change--;
            }
        }
 
        // Increment the position
        i++;
    }
 
    return ans;
}
 
// Function that counts the set bit
// in the range (L, R)
static int countSetBits(int L, int R)
{
 
    // Return the count
    return Math.Abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set bit count is " +
                   countSetBits(L, R) +"\n");
}
}
 
// This code is contributed by Rajput-Ji

Javascript


输出:
Total set bit count is 5

时间复杂度: O((L + R)*K),其中 K 是 L 和 R 中的位数。
辅助空间: O(1)

方法 3 – 棘手如果输入数字的形式为2 b – 1,例如1, 3, 7, 15等,则设置位的数量为b * 2 (b-1) 。这是因为对于所有数字0 到 2 b – 1 ,如果您对列表进行补充和翻转,您最终会得到相同的列表(一半位已设置,一半位未设置)。

如果数字没有所有设置位,则让m是最左边设置位的位置。该位置的设置位数为n – (1 << m) + 1 。其余的设置位分为两部分:

  1. (m – 1) 中的位向下定位到最左边的位变为 0 的点
  2. 该点下方的 2 (m – 1) 个数字,即上面的闭合形式。

例如:N = 6

0|0 0
0|0 1
0|1 0
0|1 1
-|--
1|0 0
1|0 1
1|1 0

从上面我们有:

  • 最左边的设置位位于位置 2(位置被视为从 0 开始)。
  • 如果我们屏蔽掉剩下的 2(最后一行右侧的“1 0”),那么第二个位置(左下角的框)的位数是 3(即 2 + 1) .
  • 0-3 的设置位(上面的右上角框)是 2*2 (2 – 1) = 4。
  • 右下角的框是我们尚未计算的剩余位,并且是可以递归计算的所有 2(右下框中最后一个条目的值)的所有数字的设置位数。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
unsigned int countSetBit(unsigned int n);
 
// Returns position of leftmost set bit
// The rightmost position is taken as 0
unsigned int getLeftmostBit(int n)
{
    int m = 0;
    while (n > 1) {
        n = n >> 1;
        m++;
    }
    return m;
}
 
// Function that gives the position of
// previous leftmost set bit in n
unsigned int getNextLeftmostBit(int n, int m)
{
    unsigned int temp = 1 << m;
    while (n < temp) {
        temp = temp >> 1;
        m--;
    }
    return m;
}
 
// Function to count the set bits between
// the two numbers N and M
unsigned int _countSetBit(unsigned int n,
                          int m)
{
    // Base Case
    if (n == 0)
        return 0;
 
    // Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1
    if (n == ((unsigned int)1 << (m + 1)) - 1)
        return (unsigned int)(m + 1) * (1 << m);
 
    // Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1)
            + countSetBit(n)
            + m * (1 << (m - 1)));
}
 
// Function that returns count of set
// bits present in all numbers from 1 to n
unsigned int countSetBit(unsigned int n)
{
    // Get the position of leftmost set
    // bit in n
    int m = getLeftmostBit(n);
 
    // Use the position
    return _countSetBit(n, m);
}
 
// Function that counts the set bits
// between L and R
int countSetBits(int L, int R)
{
    return abs(countSetBit(R)
               - countSetBit(L - 1));
}
 
// Driver Code
int main()
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set bit count is "
         << countSetBits(L, R);
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG{
 
// Returns position of leftmost set bit
// The rightmost position is taken as 0
static  int getLeftmostBit(int n)
{
    int m = 0;
    while (n > 1)
    {
        n = n >> 1;
        m++;
    }
    return m;
}
 
// Function that gives the position of
// previous leftmost set bit in n
static  int getNextLeftmostBit(int n, int m)
{
     int temp = 1 << m;
    while (n < temp)
    {
        temp = temp >> 1;
        m--;
    }
    return m;
}
 
// Function that returns count of set
// bits present in all numbers from 1 to n
static int countSetBit( int n)
{
   // Get the position of leftmost set
   // bit in n
   int m = getLeftmostBit(n);
 
   // Use the position
   return _countSetBit(n, m);
}
 
// Function to count the set bits between
// the two numbers N and M
static int _countSetBit(int n, int m)
{
    // Base Case
    if (n == 0)
        return 0;
     
    // Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1
    if (n == (( int)1 << (m + 1)) - 1)
        return ( int)(m + 1) * (1 << m);
 
    // Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1) +
            countSetBit(n) +
            m * (1 << (m - 1)));
}
 
// Function that counts the set bits
// between L and R
static int countSetBits(int L, int R)
{
    return Math.abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void main(String[] args)
{
    // Given L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.print("Total set bit count is " +
                             countSetBits(L, R));
}
}
 
// This code is contributed by sapnasingh4991

蟒蛇3

# Python program for the above approach
 
 
# Returns position of leftmost set bit
# The rightmost position is taken as 0
def getLeftmostBit(n):
    m = 0;
    while (n > 1):
        n = n >> 1;
        m += 1;
 
    return m;
 
 
# Function that gives the position of
# previous leftmost set bit in n
def getNextLeftmostBit(n, m):
    temp = 1 << m;
    while (n < temp):
        temp = temp >> 1;
        m -=1;
 
    return m;
 
 
# Function that returns count of set
# bits present in all numbers from 1 to n
def countSetBit(n):
    # Get the position of leftmost set
    # bit in n
    m = getLeftmostBit(n);
 
    # Use the position
    return _countSetBit(n, m);
 
 
# Function to count the set bits between
# the two numbers N and M
def _countSetBit(n, m):
    # Base Case
    if (n == 0):
        return 0;
 
    # Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    # If n is of the form 2^x-1
    if (n == int(1 << (m + 1)) - 1):
        return int(m + 1) * (1 << m);
 
 
    # Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1) + countSetBit(n) + m * (1 << (m - 1)));
 
 
# Function that counts the set bits
# between L and R
def countSetBits(L, R):
    return abs(countSetBit(R) - countSetBit(L - 1));
 
 
# Driver Code
if __name__ == '__main__':
    # Given L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is " , countSetBits(L, R));
 
# This code contributed by shikhasingrajput

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Returns position of leftmost set bit
// The rightmost position is taken as 0
static int getLeftmostBit(int n)
{
    int m = 0;
    while (n > 1)
    {
        n = n >> 1;
        m++;
    }
    return m;
}
 
// Function that gives the position of
// previous leftmost set bit in n
static int getNextLeftmostBit(int n, int m)
{
    int temp = 1 << m;
    while (n < temp)
    {
        temp = temp >> 1;
        m--;
    }
    return m;
}
 
// Function that returns count of set
// bits present in all numbers from 1 to n
static int countSetBit(int n)
{
     
    // Get the position of leftmost set
    // bit in n
    int m = getLeftmostBit(n);
     
    // Use the position
    return _countSetBit(n, m);
}
 
// Function to count the set bits between
// the two numbers N and M
static int _countSetBit(int n, int m)
{
     
    // Base Case
    if (n == 0)
        return 0;
     
    // Get position of next leftmost set bit
    m = getNextLeftmostBit(n, m);
 
    // If n is of the form 2^x-1
    if (n == (( int)1 << (m + 1)) - 1)
        return ( int)(m + 1) * (1 << m);
 
    // Update n for next recursive call
    n = n - (1 << m);
    return ((n + 1) +
            countSetBit(n) +
            m * (1 << (m - 1)));
}
 
// Function that counts the set bits
// between L and R
static int countSetBits(int L, int R)
{
    return Math.Abs(countSetBit(R) -
                    countSetBit(L - 1));
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given L and R
    int L = 3, R = 5;
 
    // Function call
    Console.Write("Total set bit count is " +
                          countSetBits(L, R));
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出:
Total set bit count is 5

时间复杂度: O(log N)
辅助空间: O(1)

方法 4 – 使用 setbit:在 setbit 方法中,使用最后一位对 L 到 R 范围内的每个数字的设置位逐个计数,检查到最后一位,如果设置了则增加计数,最后将其相加。
下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count set bit in range
int countSetBits(int L, int R)
{
    // Count variable
    int count = 0;
 
    for (int i = L; i <= R; i++) {
 
        // Find the set bit in Nth number
        int n = i;
        while (n > 0) {
 
            // If last bit is set
            count += (n & 1);
 
            // Left sift by one bit
            n = n >> 1;
        }
    }
 
    // Return count
    return count;
}
 
// Driver Code
int main()
{
    // Given Range L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set Bit count is "
         << countSetBits(L, R);
 
    return 0;
}

Java

// Java program for the above approach
class GFG{
   
// Function to count set bit in range
static int countSetBits(int L, int R)
{
    // Count variable
    int count = 0;
  
    for (int i = L; i <= R; i++)
    {
  
        // Find the set bit in Nth number
        int n = i;
        while (n > 0)
        {
  
            // If last bit is set
            count += (n & 1);
  
            // Left sift by one bit
            n = n >> 1;
        }
    }
  
    // Return count
    return count;
}
  
// Driver Code
public static void main(String[] args)
{
    // Given Range L and R
    int L = 3, R = 5;
  
    // Function Call
    System.out.print("Total set Bit count is " +
                             countSetBits(L, R));
}
}
 
// This code is contributed by Ritik Bansal

蟒蛇3

# Python3 program for the above approach
 
# Function to count set bit in range
def countSetBits(L, R):
     
    # Count variable
    count = 0;
 
    for i in range(L, R + 1):
 
        # Find the set bit in Nth number
        n = i;
        while (n > 0):
 
            # If last bit is set
            count += (n & 1);
 
            # Left sift by one bit
            n = n >> 1;
 
    # Return count
    return count;
 
# Driver Code
if __name__ == '__main__':
     
    # Given range L and R
    L = 3; R = 5;
 
    # Function call
    print("Total set Bit count is ",
           countSetBits(L, R));
     
# This code is contributed by Amit Katiyar

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to count set bit in range
static int countSetBits(int L, int R)
{
     
    // Count Variable
    int count = 0;
 
    for(int i = L; i <= R; i++)
    {
         
        // Find the set bit in Nth number
        int n = i;
         
        while (n > 0)
        {
             
            // If last bit is set
            count += (n & 1);
 
            // Left sift by one bit
            n = n >> 1;
        }
    }
 
    // Return count
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given Range L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set Bit count is " +
                   countSetBits(L, R));
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出:
Total set Bit count is 5

时间复杂度: O(N*logN)
辅助空间: O(1)

方法 5 – 使用 STL __builtin_popcount()函数 STL 提供了一个内置函数来计算整数中的设置位,因此这里为LR范围内的每个数字调用该函数并计算设置位。

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count set bit in [L, R]
int countSetBits(int L, int R)
{
    // Variable for count set
    // bit in range
    int count = 0;
 
    // Count set bit for all
    // number in range
    for (int i = L; i <= R; i++) {
 
        // Use inbuilt function
        count += __builtin_popcount(i);
    }
 
    return count;
}
 
// Driver Code
int main()
{
    // Given range L and R
    int L = 3, R = 5;
 
    // Function Call
    cout << "Total set bit count is "
         << countSetBits(L, R);
    return 0;
}

Java

// Java program for the above approach
class GFG{
 
// Function to count set bit in [L, R]
static int countSetBits(int L, int R)
{
    // Variable for count set
    // bit in range
    int count = 0;
 
    // Count set bit for all
    // number in range
    for (int i = L; i <= R; i++)
    {
 
        // Use inbuilt function
        count += Integer.bitCount(i);
    }
 
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given range L and R
    int L = 3, R = 5;
 
    // Function Call
    System.out.print("Total set bit count is " +
                            countSetBits(L, R));
}
}
 
// This code is contributed by Rajput-Ji

蟒蛇3

# Python3 program for the above approach
 
# Function to count set bit in [L, R]
def countSetBits(L, R):
   
    # Variable for count set
    # bit in range
    count = 0;
 
    # Count set bit for all
    # number in range
    for i in range(L, R + 1):
       
        # Use inbuilt function
        count += countSetBit(i);
 
    return count;
 
def  countSetBit(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count
   
# Driver Code
if __name__ == '__main__':
   
    # Given range L and R
    L = 3;
    R = 5;
 
    # Function Call
    print("Total set bit count is " ,
          countSetBits(L, R));
 
# This code is contributed by sapnasingh4991

C#

// C# program for the above approach
using System;
class GFG{
 
// Function to count set bit in [L, R]
static int countSetBits(int L, int R)
{
    // Variable for count set
    // bit in range
    int count = 0;
 
    // Count set bit for all
    // number in range
    for (int i = L; i <= R; i++)
    {
 
        // Use inbuilt function
        count += countSetBits(i);
    }
 
    return count;
}
static int countSetBits(long x)
{
    int setBits = 0;
    while (x != 0)
    {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
// Driver Code
public static void Main(String[] args)
{
    // Given range L and R
    int L = 3, R = 5;
 
    // Function Call
    Console.Write("Total set bit count is " +
                         countSetBits(L, R));
}
}
 
// This code is contributed by gauravrajput1

Javascript


输出:
Total set bit count is 5

时间复杂度: O(N)
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程