How to set all bits in the given range of a number
Problem statement
Given a number , , and set all the bits of in the range of to . Here, the indexing is from the rightmost bit (or LSB). The position of LSB is .
Constraint: bit count of .
Example 1:
- Input: , ,
- Output:
Example 2:
-
Input: , ,
-
Output:
-
bin() =
-
bin() =
Setting bits of from 3rd to 5th position, we get .
Solution
The idea here is to use bitmasking. The steps to solve the problem are as follows:
- Generate a bit mask that has set bits in the range [l,r].
- Perform a bitwise OR of the mask and the given number.
How to generate the mask?
The bit mask that has set bits in the range [l,r] can be generated using the following expression.
(((1 << (l - 1)) - 1) ^ ((1 << r) - 1))
Let’s break the above expression into smaller expressions for our understanding.
- (1 << (l - 1)) - 1
- (1 << r) - 1
- Step 1 ^ Step 2
Let’s understand the working of the above expression using an example.
Consider the following example.
- Input: , ,
- Output:
| Expression | Result | Binary form |
|---|---|---|
| (1 << (l - 1)) - 1 = (1 << 2) - 1 | 4 - 1 = 3 | 00011 |
| (1 << r) - 1 = (1 << 5) - 1 | 32 - 1 = 31 | 11111 |
| 3 ^ 31 | 28 | 11100 |
So, the bit mask is , such as .
Now, performing the bitwise OR i.e .
Code
class Main{static int generateMask(int l, int r){int temp1 = (1 << (l - 1)) - 1;int temp2 = (1 << r) - 1;return (temp1 ^ temp2);}static int setBitsRange(int n, int l, int r) {int mask = generateMask(l, r);return (n | mask);}public static void main(String[] args) {int n = 34;int l = 3;int r = 5;System.out.println("Setting bits of " + n + " from positions " + l + " to " + r + " we get " + setBitsRange(n, l, r));}}
Explanation
- Lines 3–7: We define the
generateMask()method that accepts the range boundarieslandr. This method generates the bit mask using the logic mentioned above. - Lines 9–12: We define the
setBitsRange()method that generates the bit mask for givenn,l, andrby invokinggenerateMask()method and performs a bitwise OR ofnand the bit mask. - Line 18: We invoke the
setBitsRange()method withn,l, andras parameters.