How to set all odd position bits of a number
Problem statement
Given a number n, set all the odd positioned bits of n. The position of LSB is considered to be 1.
Example 1:
- Input: n=8
- Output: 13
Example 2:
- Input: n=7
- Output: 7
Solution
We’ll generate a bit mask that has all the odd positioned bits set and use the bitwise OR operation.
How do we generate a bit mask?
First, we’ll make a copy of n and call it temp. Two more variables are created as follows:
count: This is used to generate the power of2, which is used to create the mask.mask: This stores the bit mask.
The steps of the bit mask generation are as follows:
- Loop until the value of
tempis greater than zero.- If the
countis even, then we set thecount-th bit in the mask. - We increment the
countby 1. - We right shift the
tempby 1.
- If the
Code
Let's look at a code example.
class Main{static int generateMask(int n){int count = 0;int mask = 0;int temp = n;while(temp > 0){if((count & 1) != 1)mask = mask | (1 << count);count++;temp >>=1;}return mask;}static int setOddBits(int n) {int mask = generateMask(n);return (n | mask);}public static void main(String[] args) {int n = 10;System.out.println("Setting odd positioned bits of " + n + " we get " + setOddBits(n));}}
Explanation
- Lines 3–16: We define the
generateMask()method to implement the solution above to generate the bit mask. - Lines 18–21: We define the
setOddBits()method to set the odd positioned bits of a number by performing the bitwiseORof the given number, as well as the mask that we generate by callinggenerateMask(). - Line 24: We define
n. - Line 25: We call the
generateMask()method withnas the parameter.