[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));
    }
}

 

 

 

转载于:https://www.cnblogs.com/codingEskimo/p/8448114.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值