Given a number n
, set all the odd positioned bits of n
. The position of LSB is considered to be 1.
Example 1:
Example 2:
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 of 2
, which is used to create the mask.mask
: This stores the bit mask.The steps of the bit mask generation are as follows:
temp
is greater than zero.
count
is even, then we set the count
-th bit in the mask.count
by 1.temp
by 1.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));}}
generateMask()
method to implement the solution above to generate the bit mask.setOddBits()
method to set the odd positioned bits of a number by performing the bitwise OR
of the given number, as well as the mask that we generate by calling generateMask()
.n
.generateMask()
method with n
as the parameter.