Trusted answers to developer questions

Ravi

Given a number `n`

, set all the even positioned bits of `n`

.

- Input:
`n=10`

- Output:
`10`

- Input:
`n=8`

- Output:
`10`

The steps in the algorithm are as follows:

- Generate a bit mask where the even positioned bits are set.
- Perform a bitwise
`OR`

operation and mask the given number.

The steps to generate the bit mask are as follows:

- We have two variables, such as
`count`

and`mask`

. - We use a temporary variable
`temp`

in a`for`

loop, and perform the following steps until`temp`

becomes zero. The`temp`

is right-shifted until it becomes zero.- If the count is odd, we then left shift
`count`

by 1 and perform bitwise`OR`

with the`mask`

. - Then, we increment the
`count`

by 1.

- If the count is odd, we then left shift

class Main{ static int generateMask(int n){ int count = 0, mask = 0; for (int temp = n; temp > 0; temp >>= 1) { if ((count & 1) > 0) mask |= (1 << count); count++; } return mask; } static int setEvenPositionedBits(int n) { int mask = generateMask(n); return (n | mask); } public static void main(String[] args) { int n = 8; System.out.println("Setting even positioned bits of " + n + " we get " + setEvenPositionedBits(n)); } }

- Lines 3–10: We define the
`generateMask()`

method, where`n`

, the even positioned set bit mask, is generated. - Lines 12–15: We define the
`setEvenPositionedBits()`

method where all even positioned bits of`n`

are set. - Line 18: We define
`n`

. - Line 19: The
`setEvenPositionedBits()`

method is invoked with`n`

as the argument.

RELATED TAGS

bitwise

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses