Problem

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

Example

5 = (101)2 => (1010)2 = 10

Solution

public class Solution {
    /*
     * @param x: An integer
     * @return: An integer
     */
    public int swapOddEvenBits(int x) {
        //keep all odd "1"
        int odd = x & 0x55555555;
        //keep all even "1"
        int even = x & 0xaaaaaaaa;
        //shift odd "1"s left
        odd <<= 1;
        //shift even "1"s right (unsigned)
        even >>>= 1;
        return odd + even;
    }
}

linspiration
161 声望53 粉丝