Given a non-negative number n and two values l and r. The problem is to set the bits in the range l to r in the binary representation of n, i.e, to unset bits from the rightmost lth bit to the rightmost r-th bit.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Input : n = 17, l = 2, r = 3 Output : 23 (17)10 = (10001)2 (23)10 = (10111)2 The bits in the range 2 to 3 in the binary representation of 17 are set. Input : n = 50, l = 2, r = 5 Output : 62
Approach: Following are the steps:
1. Find a number 'range' that has all set bits in given range. And all other bits of this number are 0. range = (((1 << (l - 1)) - 1) ^ ((1 << (r)) - 1)); 2. Now, perform "n = n | range". This will set the bits in the range from l to r in n.
This article is contributed by Devanshu Agarwal. 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.
- Smallest number whose set bits are maximum in a given range
- Count number of set bits in a range using bitset
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits in the given range
- Set bits in N equals to M in the given range.
- Unset bits in the given range
- Copy set bits in a range
- Count set bits in a range
- Check whether all the bits are set in the given range
- Count unset bits in a range
- Check whether all the bits are unset in the given range or not
- Range query for count of set bits
- Check whether all the bits are unset in the given range
- Python | Count set bits in a range
- Check if bits in range L to R of two numbers are complement of each other or not
Improved By : Sam007