Trusted answers to developer questions

Ravi

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

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:

: This is used to generate the power of`count`

`2`

, which is used to create the mask.: This stores the bit mask.`mask`

The steps of the bit mask generation are as follows:

- Loop until the value of
`temp`

is greater than zero.- If the
`count`

is even, then we set the`count`

-th bit in the mask. - We increment the
`count`

by 1. - We right shift the
`temp`

by 1.

- If the

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)); } }

Try it out!

- 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 bitwise`OR`

of the given number, as well as the mask that we generate by calling`generateMask()`

. - Line 24: We define
`n`

. - Line 25: We call the
`generateMask()`

method with`n`

as the parameter.

RELATED TAGS

bitwise

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses