Reverse Bits
Reverse bits of a given the unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 ( Represented in binary as00111001011110000010100101000000).
Followup:
If This function is called many times, what would you optimize it?
Problem Solving Ideas:
Calculated by shifting. Here's the code:
Class Solution {public: uint32_t reversebits (uint32_t N) { uint32_t result=0; int size = sizeof (uint32_t) *8; for (int i=0; i<size; i++) { result = result << 1; result + = n%2; n=n>>1; } return result;} ;
Notice that if n is a very small number, there is no need to loop the size bit, if n is shifted to a position of 0, you can jump out of the loop. Result then left to move the remaining digits. The following is the optimized code:
Class Solution {public: uint32_t reversebits (uint32_t N) { uint32_t result=0; int size = sizeof (uint32_t) *8; int i=0; Number of bits that have been moved while (n!=0) { result = result << 1; result + = n%2; n=n>>1; i++; } Result <<= size-i; return result;} ;
[Leetcode] Reverse Bits