Dare2Solve
Given a 32-bit unsigned integer, reverse its bits and return the result as an unsigned integer.
The problem requires reversing the bits of a given 32-bit unsigned integer. By iterating through each bit of the input number, we can construct the reversed bit sequence one bit at a time.
0
.n & 1
and add it to the result.O(1), because we always loop exactly 32 times, regardless of the input.
O(1), because we use a constant amount of space.
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for (int i = 0; i < 32; ++i) {
result = (result << 1) | (n & 1);
n >>= 1;
}
return result;
}
};
class Solution:
def reverseBits(self, n: int) -> int:
result = 0
for i in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return result
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; ++i) {
result = (result << 1) | (n & 1);
n >>= 1;
}
return result;
}
}
var reverseBits = function(n) {
let result = 0;
for (let i=0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>= 1;
}
return result >>> 0;
};