# C++ 4ms optimized

• ``````    //reverse pattern
//0000 => 0000 = 0
//0001 => 1000 = 8
//0010 => 0100 = 4
//0011 => 1100 = C
//0100 => 0010 = 2
//0101 => 1010 = A
//0110 => 0110 = 6
//0111 => 1110 = E
//1000 => 0001 = 1
//1001 => 1001 = 9
//1010 => 0101 = 5
//1011 => 1101 = D
//1100 => 0011 = 3
//1101 => 1011 = B
//1110 => 0111 = 7
//1111 => 1111 = F
``````

We create a 64 bits number that contains all the transformation for the 16 hex signs, then we take the 4 last bits of n (lsb), multiply the value by 4 to find the offset to look at in the reference number, and shift the result to the first place ( << 28).
Repeat than 8 times with a 4 bits shift and a logic OR each time to get the 32 bits correctly reversed.

This is to avoid reversing each single bit each time a number has to be reversed.

``````class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint64_t reverseTable = 0xF7B3D591E6A2C480;
uint32_t result = 0;
for(int i = 0; i < 32 ; i+=4)
result |= (reverseTable >> (4 * (n >> i & 0x0f)) & 0x0f) << 28-i;
return result;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.