Given a 32 bit integer input x
, swap its odd and even bits and return the resulting integer.
(e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).
For example:
x = 5, Binary code = 0101
swapOddEvenBits(5) --> 10
Binary representation of 10 = 1010
|
operator.
1. First mask (clear) all the odd bits with 10101010 (0xAA)
and shift them to the right by 1
.
2. Mask all the even bits with 01010101 (0x55)
and shift them to the left by 1
.
3. Bitswise OR |
the outputs of the first and second steps to reach the final result.
public int swapOddEvenBits(int x) { }
C
Java
Python