题目地址:
https://leetcode.com/problems/reverse-bits/
给定一个无符号 32 32 32位整数,求其二进制位左右翻转后的数。直接模拟就行。
代码如下:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
res <<= 1;
res += n & 1;
n >>>= 1;
}
return res;
}
}
时空复杂度 O ( 1 ) O(1) O(1)。
C++:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t x = 0;
for (int i = 0; i < 32; i++)
x = (x << 1) | (n >> i & 1);
return x;
}
};
时空复杂度一样。