Reversed given 32-bit unsigned binary integer.
Example 1:
Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 explained: input binary string 00000010100101000001111010011100 unsigned integer 43261596 , the flow returns 964,176,192, which is expressed in binary form 00111001011110000010100101000000 .
Example 2:
Input: 11111111111111111111111111111101 Output: 10111111111111111111111111111111 explained: input binary string 11111111111111111111111111111101 unsigned integer 4294967293, thus returns its binary representation is 3221225471 10101111110010110010011101101001.
prompt:
- Please note that in some languages (such as Java), there is no unsigned integer type. In this case, the input and output will be designated as a signed integer type, and should not affect your implementation, because both the integer is signed or unsigned, its binary representation of the interior is the same.
- In Java, the compiler uses the twos complement notation to represent signed integers. Thus, in the above example 2 , the input represents a signed integer
-3
, outputs a signed integer-1073741825
.
Advanced :
If you repeatedly call this function, you will how to optimize your algorithm?
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int m = 0;
for(int i=0;i<32;i++) {
m<<=1;
m = m |(n&1);
n>>=1;
}
return m;
}
}