In this approach, we utilize bitwise operations to reverse the bits. We iterate through each bit of the number from the least significant bit (LSB) to the most significant bit (MSB), shifting the resultant bits to the left and using the bitwise OR operation to set the bits in the reversed order.
Time Complexity: O(1) because the operation involves a fixed number of 32 iterations, and each operation within the loop is O(1).
Space Complexity: O(1) since we only use a constant amount of additional space for variables.
1#include <cstdint>
2
3uint32_t reverseBits(uint32_t n) {
4 uint32_t result = 0;
5 for (int i = 0; i < 32; i++) {
6 result = (result << 1) | (n & 1);
7 n >>= 1;
8 }
9 return result;
10}
This C++ solution uses the same logic as the C implementation, making use of bitwise operations to reverse the bits in a given unsigned 32-bit number. Each bit is processed and added to the result in reversed order.
This approach could be optimized by precomputing masks that handle groups of bits. This reduces the need for iterating through each bit and instead processes larger chunks of bits through bit manipulation techniques.
Time Complexity: O(1).
Space Complexity: O(1).
1public class Solution {
2 public uint reverseBits(uint n) {
3 n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1);
4 n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2);
5 n = ((n >> 4) & 0x0F0F0F0F) | ((n & 0x0F0F0F0F) << 4);
6 n = ((n >> 8) & 0x00FF00FF) | ((n & 0x00FF00FF) << 8);
7 n = ((n >> 16) & 0x0000FFFF) | ((n & 0x0000FFFF) << 16);
8 return n;
9 }
10}
This C# approach uses precomputed masks for reversing bits, performing fewer operations to produce the reversed value efficiently, particularly valuable when the function is called numerous times.