问题描述:将输入的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:
1 | uint32_t reverseBits(uint32_t n) { |
总结
Reverse Bits以及之前的Hamming Weight均是练习按位操作,需理解及注意的地方:
- 二进制位运算效率较高。
- 正负数的二进制表示,负数时为补码表示,注意特定位数的有符号整数的范围。
- 注意对越界情况的判断及处理。