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.
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:
- 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.
- Calculate new_num = n & num.
- If new_num == 0, return “Yes” (all bits are unset in the given range).
- Else return “No” (all bits are not unset in the given range).
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 firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check whether all the bits are unset in the given range
- Unset bits in the given range
- Count unset bits in a range
- Python | Count unset bits in a range
- Check whether the bit at given position is set or unset
- Check whether all the bits are set in the given range
- Check if a number has same number of set and unset bits
- Count total unset bits in all the numbers from 1 to N
- Unset least significant K bits of a given number
- Check whether bits are in alternate pattern in the given range | Set-2
- Check whether bits are in alternate pattern in the given range
- Find the largest number with n set and m unset bits
- Find the smallest number with n set and m unset bits
- Count unset bits of a number
- Unset the last m bits
- Check if all bits can be made same by flipping two consecutive bits
- Count of numbers having only one unset bit in a range [L,R]
- Check if bits in range L to R of two numbers are complement of each other or not
- Queries to check whether all the elements in the given range occurs even number of times
- Check if bits of a number has count of consecutive set bits in increasing order