LeetCode 第 190 題 (Reverse Bits)

liyuanbhu發表於2016-04-18

LeetCode 第 190 題 (Reverse Bits)

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

將一個整數按位翻轉,題目並不難。最簡單的辦法就是用個迴圈遍歷各個位,然後將其放置到合適的位置。下面是程式碼:

uint32_t reverseBits(uint32_t n)
{
    uint32_t ret = 0;
    for(int i = 0; i < 32; i++)
    {
        ret = (ret << 1) + (n & 1);
        n = n >> 1;
    }
    return ret;
}

這裡需要注意的是運算子的優先順序, “<<” 和 “&” 的優先順序都很低,所以要加括號,這個地方很容易出錯。

除了這種迴圈置位方法,還可以用查表法。我們沒法將 32 位整數列舉一遍,但是可以列舉小一點的整數。比如下面程式這樣四位四位的處理。

class Solution {
public:
    uint8_t reverseChar(uint8_t c)
    {
        const uint8_t table[16] = {0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE, 0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF};
        return (table[c & 0xF] << 4) + table[c >> 4];
    }
    uint32_t reverseBits(uint32_t n) {
        uint8_t * p = (uint8_t *)&n;
        uint32_t ret;
        uint8_t * q = (uint8_t *) &ret;
        q[0] = reverseChar(p[3]);
        q[1] = reverseChar(p[2]);
        q[2] = reverseChar(p[1]);
        q[3] = reverseChar(p[0]);
        return ret;
    }
};

相關文章