欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LintCode 236: Swap Bits (位运算经典题)

程序员文章站 2022-07-05 12:59:04
...

我之前的做法太繁琐。

class Solution {
public:
    /*
     * @param x: An integer
     * @return: An integer
     */
    int swapOddEvenBits(int x) {
        int len = sizeof(int) * 8;
        for (int i = 0; i < len; i += 2) {
            int even = (x >> i) & 0x1;
            int odd = (x >> i + 1) & 0x1;
            if (odd != even) {
                if (even == 1) {
                    x &= ~(0x1 << i);  //clear i th bit
                    x |= (0x1 << (i + 1)); //set the i+1 th bit
                } else {
                    x &= ~(0x1 << (i + 1));  //clear i+1 th bit
                    x |= (0x1 << i); //set the i th bit
                }
            } 
        }
        
        return x;
    }
};

发现最简单的做法就是:

    int swapOddEvenBits(int x) {
        return ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
    }
相关标签: LintCode