VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-unset-bits-range/

⇱ Count unset bits in a range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count unset bits in a range

Last Updated : 15 Jun, 2022

Given a non-negative number n and two values l and r. The problem is to count the number of unset bits in the range l to r in the binary representation of n, i.e, to count unset bits from the rightmost lth bit to the rightmost rth bit.
Examples: 
 

Input : n = 42, l = 2, r = 5
Output : 2
(42)10 = (101010)2
There are '2' unset bits in the range 2 to 5.

Input : n = 80, l = 1, r = 4
Output : 4


 


Approach: Following are the steps:
 

  1. 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.
  2. Count number of set bits in the number (n & num). Refer this post. Let it be count.
  3. Calculate ans = (r - l + 1) - count.
  4. Return ans.


 

Output: 

4

Time Complexity: O(log n)
Space Complexity: O(1)

Comment
Article Tags: