1.题目
Reverse bits of a given 32 bits unsigned integer.
给一个无符号32位整数,翻转所有bit并返回翻转的结果。
For example, given
input 43261596 ( 00000010100101000001111010011100)
return 964176192 (00111001011110000010100101000000).
2.分析
设原数A,结果B,A的最低位是B的最高位。
考虑遍历A的每一个bit来求得B。
因为是2进制,所以用位运算比较快。
3.代码
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t m = 0;
int i = 0;
for (int i = 0; i < 32; i++) {
m <<= 1;
m |= n & 1;
n >>= 1;
}
cout << m << endl;
return m;
}
};
最开始没有用位运算,是这样写的
uint32_t reverseBits(uint32_t n) {
vector<int> bits(32, 0);
uint32_t res = 0;
int i = 31;
while (n) {
bits[i] = n % 2;
n /= 2;
res = res * 2 + bits[i];
--i;
}
while (i>=0) {
res *= 2;
--i;
}
return res;
}