[LintCode] Swap Bits
文章目录
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;
}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论