Count set bits in a range - GeeksforGeeks

28 Apr, 2021
Given a non-negative number n and two values l and r. The problem is to count the number of set bits in the range l to r in the binary representation of n, i.e, to count set bits from the rightmost lth bit to the rightmost rth bit. Constraint: 1 <= l <= r <= number of bits in the binary representation of n.Examples:  
Input : n = 42, l = 2, r = 5
Output : 2
(42)10 = (101010)2
There are '2' set bits in the range 2 to 5.

Input : n = 79, l = 1, r = 4
Output : 4
 
Approach: Following are the steps: 
Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number num having r number of bits and bits in the range l to r are the only set bits.Count number of set bits in the number (n & num). Refer this post.
Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number num having r number of bits and bits in the range l to r are the only set bits.
Count number of set bits in the number (n & num). Refer this post.
 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to count set bits in the// given range#include <bits/stdc++.h> using namespace std; // Function to get no of set bits in the// binary representation of 'n'unsigned int countSetBits(int n){    unsigned int count = 0;    while (n) {        n &= (n - 1);        count++;    }    return count;} // function to count set bits in the given rangeunsigned int countSetBitsInGivenRange(unsigned int n,                       unsigned int l, unsigned int r){    // calculating a number 'num' having 'r' number    // of bits and bits in the range l to r are the    // only set bits    int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);     // returns number of set bits in the range    // 'l' to 'r' in 'n'    return countSetBits(n & num);} // Driver program to test aboveint main(){    unsigned int n = 42;    unsigned int l = 2, r = 5;    cout << countSetBitsInGivenRange(n, l, r);    return 0;}
// Java implementation to count set bits in the// given rangeclass GFG {         // Function to get no of set bits in the    // binary representation of 'n'    static int countSetBits(int n)    {        int count = 0;        while (n > 0) {            n &= (n - 1);            count++;        }                 return count;    }     // function to count set bits in the given range    static int countSetBitsInGivenRange(int n, int l, int r)    {                 // calculating a number 'num' having 'r' number        // of bits and bits in the range l to r are the        // only set bits        int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);         // returns number of set bits in the range        // 'l' to 'r' in 'n'        return countSetBits(n & num);    }         // Driver code    public static void main(String[] args)    {        int n = 42;        int l = 2, r = 5;                 System.out.print(countSetBitsInGivenRange(n, l, r));    }} // This code is contributed by Anant Agarwal.
# Python3 implementation to count# set bits in the given range # Function to get no of set bits in the# binary representation of 'n'def countSetBits(n):    count = 0    while (n):        n &= (n - 1)        count = count + 1         return count  # function to count set bits in# the given rangedef countSetBitsInGivenRange(n, l,  r):     # calculating a number 'num' having    # 'r' number of bits and bits in the    # range l to r are the  only set bits    num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)      # returns number of set bits in the range    # 'l' to 'r' in 'n'    return countSetBits(n & num) # Driver program to test aboven = 42l = 2r = 5ans = countSetBitsInGivenRange(n, l, r)print (ans) # This code is contributed by Saloni Gupta.
// C# implementation to count set bits in the// given rangeusing System; class GFG {         // Function to get no of set bits in the    // binary representation of 'n'    static int countSetBits(int n)    {        int count = 0;                 while (n>0) {            n &= (n - 1);            count++;        }                 return count;    }          // function to count set bits in the given range    static int countSetBitsInGivenRange(int n,                                       int l, int r)    {                 // calculating a number 'num' having 'r' number        // of bits and bits in the range l to r are the        // only set bits        int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);              // returns number of set bits in the range        // 'l' to 'r' in 'n'        return countSetBits(n & num);    }         //Driver code    public static void Main()    {        int n = 42;        int l = 2, r = 5;                 Console.WriteLine(countSetBitsInGivenRange(n, l, r));    }} // This code is contributed by Anant Agarwal.
<?php// PHP implementation to count// set bits in the given range // Function to get no of set bits in// the binary representation of 'n'function countSetBits($n){    $count = 0;    while ($n)    {        $n &= ($n - 1);        $count++;    }    return $count;} // function to count set// bits in the given rangefunction countSetBitsInGivenRange($n, $l, $r){         // calculating a number 'num'    // having 'r' number of bits    // and bits in the range l to    // r are the only set bits    $num = ((1 << $r) - 1) ^           ((1 << ($l - 1)) - 1);     // returns number of    // set bits in the range    // 'l' to 'r' in 'n'    return countSetBits($n & $num);}     // Driver Code    $n = 42;    $l = 2;    $r = 5;    echo countSetBitsInGivenRange($n, $l, $r); // This code is contributed by Ajit.?>
<script> // Javascript implementation to// count set bits in the// given range  // Function to get no of set bits in the    // binary representation of 'n'    function countSetBits(n)    {        let count = 0;        while (n > 0) {            n &= (n - 1);            count++;        }                   return count;    }       // function to count set    // bits in the given range    function countSetBitsInGivenRange(n, l, r)    {                   // calculating a number 'num'        // having 'r' number        // of bits and bits in the        // range l to r are the        // only set bits        let num = ((1 << r) - 1) ^                   ((1 << (l - 1)) - 1);           // returns number of set        // bits in the range        // 'l' to 'r' in 'n'        return countSetBits(n & num);    } // driver program         let n = 42;        let l = 2, r = 5;                document.write(countSetBitsInGivenRange(n, l, r));   </script>
Output:  
2
 
YouTubeGeeksforGeeks500K subscribersCount set bits in a range | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WhzCrXeDLco" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
jit_t
sanjoy_62
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Bits manipulation (Important tactics)
Josephus problem | Set 1 (A O(n) Solution)
Write an Efficient C Program to Reverse Bits of a Number
C++ bitset and its application
Check whether K-th bit is set or not