190. Reverse Bits
Problem
Reverse the bits of a 32-bit unsigned integer.
Example: 43261596 (00000010100101000001111010011100) → 964176192 (00111001011110000010100101000000)
Constraints: follow-up: the function is called many times.
Shift the result left and append the lowest bit of n, 32 times. Java: use >>> (unsigned shift).
Complexity: O(32).
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for _ in range(32):
res = (res << 1) | (n & 1)
n >>= 1
return res
assert Solution().reverseBits(43261596) == 964176192
assert Solution().reverseBits(4294967293) == 3221225471
class Solution {
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
res = (res << 1) | (n & 1);
n >>>= 1;
}
return res;
}
}
func reverseBits(num uint32) uint32 {
var res uint32
for i := 0; i < 32; i++ {
res = res<<1 | num&1 // shift the lowest bit of num into res
num >>= 1
}
return res
}