LeetCode OJ-190. Reverse Bits

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?

Related problem: Reverse Integer

题意大致是要将无符号整型的二进制位倒置,做法比较粗糙,直接取得每个bit的值,再将(31 - i)个位置的值置为该bit的值,i为原数二进制位的索引。具体代码如下:
uint32_t reverseBits(uint32_t n) {
    int i;
    int res = 0;
    for (i = 0; i < 32; ++i) {
        if ((n & (1 << i)) != 0) {
            res |= (1 << (31 - i));
        }
    }
    
    return res;
}


你可能感兴趣的:(OJ,leetcode,ACM,位运算)