[LintCode] Swap Bits

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

思路:

这道题需要知道的技巧是哪个数是even number mask,哪个是odd number mask

对于32位:0xaaaaaaaa 是所以偶数位上是1,奇数位上是0。0x55555555 是所有奇数位上为1,偶数位上为0

1)x & 0xaaaaaaaa -> 得到x中所有偶数位为1的结果, x & 0x55555555 -> 得到x中所有奇数位为1的结果

2)偶数位算数右移(结果是正数)奇数位左移

3)或操作使得移动后的数位得以保存。

 

public class Solution {
    /*
     * @param x: An integer
     * @return: An integer
     */
    public int swapOddEvenBits(int x) {
        // write your code here
        
        //get all even bits of x
        int even = x & 0xaaaaaaaa;
        
        //get all odd bits of x
        int odd = x & 0x55555555;
        return ((even >>> 1) | (odd << 1));
    }
}

 

 

 

你可能感兴趣的:([LintCode] Swap Bits)