study-leetcode-190 颠倒二进制位
1.题目描述
颠倒给定的 32 位无符号整数的二进制位。
2.设计思想
取余法。
3.相关代码
python
class Solution:
def reverseBits(self, n: int) -> int:
result = 0
i = 32
while i:
result <<= 1
result += n % 2
n >>= 1
i -= 1
return result
C++
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
int i = 32;
while(i--){
result <<= 1;
result += n % 2;
n >>= 1;
}
return result;
}
};
4.算法效率
时间复杂度:O( n )
空间复杂度:O( 1 )