Given two integers L and R. Determine the bitwise OR of all the integers in the range [L, R] (both inclusive).
Input: L = 3, R = 8 Output: 15 3 | 4 | 5 | 6 | 7 | 8 = 15 Input: L = 12, R = 18 Output: 31 12 | 13 | 14 | 15 | 16 | 17 | 18 = 31
A naive approach is to traverse through all the integers between L and R and do bitwise OR of all the numbers.
An efficient approach be to follow the following steps:
- Find the position of Most Significant Bit (MSB) in both the numbers (L and R)
- If the position of both MSBs are different, set all the bits from the max(MSB1, MSB2) including this different bit upto Oth bit i.e. add the value (1 << i) for all 0 ≤ i ≤ max(MSB1, MSB2) in the answer.
- If the position of both MSBs are same, then
- Set this bit corresponding to MSB or add the value (1 << MSB) in the answer.
- Subtract the value (1 << MSB) from both the numbers (L and R).
- Repeat the steps 1, 2 and 3.
Given below is the working of the above algorithm when L = 18 and R = 21.
L = 18, R = 21 The result is initially 0. The position of Most Significant Bit in L = 4 Position of Most Significant Bit in R = 4 Since positions are same, add value (1 << 4) i.e. 16 to the result. Subtract (1 << 4) from L, L becomes 2. Subtract (1 << 4) from R, R becomes 5. Now, Position of MSB in L is 1 Position of MSB in R is 2 Since positions are different all value (1 << i) for all 0 ≤ i ≤ max(MSB1, MSB2) i.e. Add ((1 << 2) + (1 << 1) + (1 << 0)) = 7 Hence, final result is 16 + 7 = 23.
Below is the implementation of above approach.
Time Complexity: O(N), where N is the Most significant bit.
- Bitwise and (or &) of a range
- Maximum Bitwise OR pair from a range
- Maximum possible Bitwise OR of the two numbers from the range [L, R]
- Maximum Bitwise AND pair from given range
- Queries for bitwise AND in the index range [L, R] of the given array
- Queries for bitwise OR in the index range [L, R] of the given array
- Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
- Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs
- Find subsequences with maximum Bitwise AND and Bitwise OR
- Sum of bitwise AND of all subarrays
- Sum of bitwise OR of all possible subsets of given set
- Bitwise Operators in C/C++
- Bitwise Sieve
- Sum of bitwise OR of all subarrays
- Bitwise AND of all the odd numbers from 1 to N
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.