Unset Bits in Range

Last Updated : 3 Aug, 2026

Given a non-negative integer n and two integers l and r, count the number of unset bits (0s) in the binary representation of n from the lth bit to the rth bit (inclusive), where the least significant bit is considered as the 1st bit.

Examples: 

Input: n = 42, l = 2, r = 5
Output: 2
Explanation: The binary representation of 42 is 101010. The bits from positions 2 to 5 are 1010, which contain 2 unset bits.

Input: n = 80, l = 1, r = 4
Output: 4
Explanation: The binary representation of 80 is 1010000. The bits from positions 1 to 4 are 0000, which contain 4 unset bits.

Try It Yourself
redirect icon

Using Bit Manipulation - O(r - l + 1) Time and O(1) Space

The idea is to examine each bit in the required range using bitwise right shift and AND with 1. If the extracted bit is 0, count it as an unset bit.

Working of Approach:

  • Initialize a variable res to store the number of unset bits.
  • Traverse every bit position from l to r.
  • For each position pos, right shift n by (pos - 1) places and perform AND with 1 to extract that bit.
  • If the extracted bit is 0, increment res.
  • After checking all the required bit positions, return res as the answer.

Let us understand with an example:
Input: n = 80, l = 1, r = 4

  • The binary representation of 80 is 1010000.
  • Traverse the bit positions from 1 to 4 and extract each bit using ((n >> (pos - 1)) & 1).
  • The bits at positions 1, 2, 3, and 4 are 0, 0, 0, and 0. Hence, the count of unset bits becomes 4.
  • Hence, the final answer is 4.
C++
#include <iostream>
using namespace std;

int countUnsetBits(int n, int l, int r)
{
    int res = 0;
    for (int pos = l; pos <= r; pos++)
    {

        // Check whether the current bit is unset.
        if (((n >> (pos - 1)) & 1) == 0)
        {
            res++;
        }
    }
    return res;
}

int main()
{
    int n = 80, l = 1, r = 4;

    cout << countUnsetBits(n, l, r);

    return 0;
}
Java
public class GFG {
    public static int countUnsetBits(int n, int l, int r)
    {
        int res = 0;
        for (int pos = l; pos <= r; pos++) {
            // Check whether the current bit is unset.
            if (((n >> (pos - 1)) & 1) == 0) {
                res++;
            }
        }
        return res;
    }

    public static void main(String[] args)
    {
        int n = 80, l = 1, r = 4;
        System.out.println(countUnsetBits(n, l, r));
    }
}
Python
def countUnsetBits(n, l, r):
    res = 0
    for pos in range(l, r + 1):
        # Check whether the current bit is unset.
        if ((n >> (pos - 1)) & 1) == 0:
            res += 1
    return res


if __name__ == '__main__':
    n = 80
    l = 1
    r = 4
    print(countUnsetBits(n, l, r))
C#
using System;

public class GFG {
    public static int countUnsetBits(int n, int l, int r)
    {
        int res = 0;
        for (int pos = l; pos <= r; pos++) {
            // Check whether the current bit is unset.
            if (((n >> (pos - 1)) & 1) == 0) {
                res++;
            }
        }
        return res;
    }

    public static void Main()
    {
        int n = 80, l = 1, r = 4;
        Console.WriteLine(countUnsetBits(n, l, r));
    }
}
JavaScript
function countUnsetBits(n, l, r)
{
    let res = 0;
    for (let pos = l; pos <= r; pos++) {
        // Check whether the current bit is unset.
        if (((n >> (pos - 1)) & 1) === 0) {
            res++;
        }
    }
    return res;
}

// Driver Code
let n = 80, l = 1, r = 4;
console.log(countUnsetBits(n, l, r));

Output
4

Using Bit Masking and Set Bit Count - O(Log ((r - l + 1)) Time and O(1) Space

The idea is to isolate the bits in the given range using a bitmask and then count the number of set bits in that range. Finally subtract this count from the total number of bits in the range to obtain the count of unset bits.

Working of Approach:

  • Compute the number of bit positions in the given range as len = r - l + 1.
  • Create a bitmask with len consecutive 1s and shift it to align with positions l to r.
  • Extract the required bits from the number using bitwise AND and shift them to the least significant positions.
  • Count the number of set bits in the extracted value using __builtin_popcount().
  • Subtract the set bit count from len to obtain the number of unset bits in the given range.

Let us understand with an example:
Input: n = 80, l = 1, r = 4

  • Binary representation of 80 is 01010000, and the required range is bits 1 to 4.
  • Create the mask: ((1 << 4) - 1) << 0 = 00001111.
  • Extract the required bits: 01010000 & 00001111 = 00000000.
  • The extracted value contains 0 set bits (__builtin_popcount = 0).
  • Hence, unset bits = 4 - 0 = 4, so the answer is 4.
C++
#include <iostream>
using namespace std;

int countUnsetBits(int n, int l, int r)
{
    int len = r - l + 1;

    // Mask with 'len' 1s, shifted to positions l..r
    int mask = ((1 << len) - 1) << (l - 1);

    // Extract the bits in the range
    int bits = (n & mask) >> (l - 1);

    // Count unset bits
    return len - __builtin_popcount(bits);
}

int main()
{
    int n = 80, l = 1, r = 4;
    cout << countUnsetBits(n, l, r);
}
Java
import java.util.BitSet;

public class GFG {
    // Function to count unset bits in a range
    public static int countUnsetBits(int n, int l, int r)
    {
        int len = r - l + 1;

        // Mask with 'len' 1s, shifted to positions l..r
        int mask = ((1 << len) - 1) << (l - 1);

        // Extract the bits in the range
        int bits = (n & mask) >> (l - 1);

        // Count unset bits
        int unsetBits = 0;
        for (int i = 0; i < len; i++) {
            if (((bits >> i) & 1) == 0) {
                unsetBits++;
            }
        }
        return unsetBits;
    }

    public static void main(String[] args)
    {
        int n = 80, l = 1, r = 4;
        System.out.println(countUnsetBits(n, l, r));
    }
}
Python
def countUnsetBits(n, l, r):
    len = r - l + 1

    # Mask with 'len' 1s, shifted to positions l..r
    mask = ((1 << len) - 1) << (l - 1)

    # Extract the bits in the range
    bits = (n & mask) >> (l - 1)

    # Count unset bits
    return len - bin(bits).count('1')


if __name__ == '__main__':
    n = 80
    l = 1
    r = 4
    print(countUnsetBits(n, l, r))
C#
using System;

public class GFG {
    // Function to count unset bits in a range
    public static int countUnsetBits(int n, int l, int r)
    {
        int len = r - l + 1;

        // Mask with 'len' 1s, shifted to positions l..r
        int mask = ((1 << len) - 1) << (l - 1);

        // Extract the bits in the range
        int bits = (n & mask) >> (l - 1);

        // Count unset bits
        int unsetBits = 0;
        for (int i = 0; i < len; i++) {
            if (((bits >> i) & 1) == 0) {
                unsetBits++;
            }
        }
        return unsetBits;
    }

    public static void Main()
    {
        int n = 80, l = 1, r = 4;
        Console.WriteLine(countUnsetBits(n, l, r));
    }
}
JavaScript
function countUnsetBits(n, l, r)
{
    var len = r - l + 1;

    // Mask with 'len' 1s, shifted to positions l..r
    var mask = ((1 << len) - 1) << (l - 1);

    // Extract the bits in the range
    var bits = (n & mask) >> (l - 1);

    // Count unset bits
    var unsetBits = 0;
    for (var i = 0; i < len; i++) {
        if (((bits >> i) & 1) === 0) {
            unsetBits++;
        }
    }
    return unsetBits;
}

// Driver Code
var n = 80, l = 1, r = 4;
console.log(countUnsetBits(n, l, r));

Output
4
Comment