[LeetCode]190. Reverse Bits | 按位反转操作问题解法

题目来源:LeetCode: Reverse Bits

问题描述:将输入的32位无符号整数对应的二进制数,按位反转后返回对应的整数。

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

方案1:

Note:按位操作,对输入从后向前逐一处理。

1
2
3
4
5
6
7
8
9
10
11
uint32_t reverseBits(uint32_t n) {
uint32_t out=0;
int k=32;
while(k--)
{
out <<= 1 ;
out += n&1 ;
n >>= 1 ;
}
return out;
}

总结

Reverse Bits以及之前的Hamming Weight均是练习按位操作,需理解及注意的地方:

  1. 二进制位运算效率较高。
  2. 正负数的二进制表示,负数时为补码表示,注意特定位数的有符号整数的范围。
  3. 注意对越界情况的判断及处理。