Reverse bits of an integer
Problem:Reverse the bits of an integer such that if the integer was 01001, then it should become 10010.
If there were only 2 bits, this could be done just by swapping the 2 bits.
If there were 4 bits, then we could swap first 2 bits with last 2 bits and then swap the 2 groups of 2 bits each.
Similarly, for a 32 bit integer, we can swap first 16 bits with last 16 bits. Then in each 16 bit group, we can swap 8 bits with other 8 bits and so on.
Below is the execution for an 8 bit integer:
Thus, the bits would be reversed in log(32)=5 operations.
|Email:||(Your email is not shared with anybody)|