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
分析:题目要求将一个32位无符号整数对应的二进制串反转,求反转后的二进制串对应的32位无符号整数。
首先我的思路是先将整数转换为其二进制形式,然后将二进制串反转,再将反转二进制串转换为十进制整数。
其中主要通过位运算来提高运算速度。
程序中的所有数在计算机内存中都是以二进制的形式储存的。位运算说穿了,就是直接对整数在内存中的二进制位进行操作。比如,and运算本来是一个逻辑运算符,但整数与整数之间也可以进行and运算。举个例子,6的二进制是110,11的二进制是1011,那么6 and 11的结果就是2,它是二进制对应位进行逻辑运算的结果(0表示False,1表示True,空位都当0处理)
含义 | Pascal语言 | C语言 | Java |
---|---|---|---|
按位与 | a and b | a & b | a & b |
按位或 | a or b | a | b | a | b |
按位异或 | a xor b | a ^ b | a ^ b |
按位取反 | not a | ~a | ~a |
左移 | a shl b | a << b | a << b |
带符号右移 | a shr b | a >> b | a >> b |
无符号右移 | a>>> b |
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
vector
bits;
uint32_t result =0;
while(n){
bits.push_back(n&1);
n = n>>1;
}
for(int i=0;i
方法二:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result =0;
for(int i=0;i<32;i++){
result |= (((n>>i)&1)<< (31-i));
}
return result;
}
};