Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Analysis:
The idea is to extract each bit of the number by shifting the number right one bit per time and AND with 0x1. Each AND, we record the result bit as the least significant bit of the final result Res. In order to store all AND results, we need to left shift the Res one bit per AND operation and OR it with the AND result.
C++:
uint32_t reverseBits(uint32_t n) {
uint32_t res=0;
for(int i=0; i<sizeof(n)*8; i++){
res<<=1;
res |= (n&0x1);
n>>=1;
}
return res;
}
Cost:
O(1)
Cost:
O(1)
No comments:
Post a Comment