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).
# Python 3 implementation to check whether
# all the bits are unset in the given range
# or not
# function to check whether all the bits
# are unset in the given range or not
def allBitsSetInTheGivenRange(n, l, r):
# calculating a number ‘num’ having ‘r’
# number of bits and bits in the range l
# to r are the only set bits
num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1) # new number which will only have # one or more set bits in the # range l to r and nowhere else new_num = n & num # if new num is 0, then all bits # are unset in the given range if (new_num == 0): return "Yes" # else all bits are not unset return "No" # Driver Code if __name__ == "__main__": n = 17 l = 2 r = 4 print(allBitsSetInTheGivenRange(n, l, r)) # This code is contributed by ita_c [tabby title="C#"]
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.
- Write an Efficient Method to Check if a Number is Multiple of 3
- Check for Integer Overflow
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Swap all odd and even bits
- Check if a number is multiple of 9 using bitwise operators
- Check if binary representation of a number is palindrome
- Toggle all the bits of a number except k-th bit.
- Check if a given number is sparse or not