Given a non-negative number n and two values l and r. The problem is to check whether all the bits are set 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 = 22, l = 2, r = 3 Output : Yes (22)10 = (10110)2 The bits in the range 2 to 3 are all set. Input : n = 47, l = 2, r = 5 Output : No (47)10 = (101111)2 The bits in the range 2 to 5 are all not set.
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 num == new_num, return “Yes” (all bits are set in the given range).
- Else return “No” (all bits are not set 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check whether all the bits are unset in the given range
- Check whether all the bits are unset in the given range or not
- Check whether bits are in alternate pattern in the given range
- Check if bits in range L to R of two numbers are complement of each other or not
- Check whether bits are in alternate pattern in the given range | Set-2
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if all bits can be made same by flipping two consecutive bits
- Set bits in N equals to M in the given range.
- Toggle bits in the given range
- Copy set bits in a range
- Count set bits in a range
- Unset bits in the given range
- Set all the bits in given range of a number
- Count unset bits in a range
- Python | Count set bits in a range
Improved By : jit_t