VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-all-the-bits-are-unset-in-the-given-range-or-not/

⇱ Check whether all the bits are unset in the given range or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check whether all the bits are unset in the given range or not

Last Updated : 13 Jun, 2022

Given a non-negative number n and two values l and r. The problem is to check whether all the bits are unset or not in the range l to r in the binary representation of n
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples: 
 

Input : n = 17, l = 2, r = 4
Output : Yes
(17)10 = (10001)2
The bits in the range 2 to 4 are all unset.

Input : n = 36, l = 3, r = 5
Output : No
(36)10 = (100100)2
The bits in the range 3 to 5 are all not unset.


 


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. Calculate new_num = n & num.
  3. If new_num == 0, return β€œYes” (all bits are unset in the given range).
  4. Else return β€œNo” (all bits are not unset in the given range).


 

Output: 

Yes

Time Complexity : O(1) 

Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: