Given two numbers x and y, and a range [l, r] where 1 <= l, r <= 32. The task is consider set bits of y in range [l, r] and set these bits in x also. Examples :
Input : x = 10, y = 13, l = 2, r = 3 Output : x = 14 Binary representation of 10 is 1010 and that of y is 1101. There is one set bit in y at 3’rd position (in given range). After we copy this bit to x, x becomes 1110 which is binary representation of 14. Input : x = 8, y = 7, l = 1, r = 2 Output : x = 11
Source : D E Shaw Interview
Method 1 (One by one copy bits)
We can one by one find set bits of y by traversing given range. For every set bit, we OR it to existing bit of x, so that the becomes set in x, if it was not set. Below is C++ implementation.
Modified x is 14
Method 2 (Copy all bits using one bit mask)
Modified x is 14
Thanks to Ashish Rathi for suggesting this solution in a comment.
This article is contributed by Rishi. 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 if bits of a number has count of consecutive set bits in increasing order
- Print numbers having first and last bits as the only set bits
- Toggle bits of a number except first and last bits
- Check if all bits can be made same by flipping two consecutive bits
- Set bits in N equals to M in the given range.
- Check whether all the bits are set in the given range
- Set all the bits in given range of a number
- Smallest number whose set bits are maximum in a given range
- Python | Count set bits in a range
- Check whether bits are in alternate pattern in the given range | Set-2
- Range query for count of set bits
- Count number of set bits in a range using bitset
- Count total set bits in all numbers from range L to R
- Count numbers in range [L, R] having K consecutive set bits
- Count set bits in a range
- Toggle bits in the given range
- Unset bits in the given range
- Check whether all the bits are unset in the given range or not
- Count unset bits in a range
- Python | Count unset bits in a range