title :
Reverse bits of a given the unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represent Ed in binary as 00111001011110000010100101000000).
Follow up:
If This function is called many times, what would you optimize it?
Ideas:
The idea of the problem is similar to the reverse integer, here is the binary number to transpose, we can use the shift method, the original number of the last one:N & 1
Then keep moving right:n=n>>1
And the last one to move the number of results to the left or the number of primitives:res=res<<1; res=res | (N & 1)
Since the number of bits is determined, it is only necessary to shift 31 times.
The code is as follows:
Public classSolution {//You need treat n as an unsigned value Public intReversebits (intN) {intres= N & 1; for(inti=1;i<=31;i++) {n=n>>1;//Keep moving to the rightres=res<<1;//Keep moving to the leftRes=res | (N & 1); } returnRes; }}
Reference:http://pisxw.com/algorithm/reverse-bits.html
*reverse Bits