这题很简单但是老是没过 因为 运算符优先级搞错
要有括号
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
if (n == 0)
return 0;
uint32_t bit;
uint32_t result = 0;
uint32_t counter = 0;
while (counter < 32)
{
bit = n & 1;
result = (result << 1) + bit; //就是这里!!!
n = n >> 1;
++counter;
}
return result;
}
};
可以精简
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
if (n == 0)
return 0;
uint32_t result = 0;
uint32_t counter = 0;
while (counter < 32)
{
result = (result << 1) + ((n >> (counter++)) & 1);
}
return result;
}
};