Leetcode: 190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Example:
Input: 43261596
Output: 964176192
Explanation: 43261596
represented in binary as 00000010100101000001111010011100
,
return 964176192
represented in binary as 00111001011110000010100101000000
.
Follow up:
If this function is called many times, how would you optimize it?
Hints:
- & Operator:
only 1 and 1 can be 1, others will be 0, like 01001 & 00001 = 00001 - | Operator:
only 0 and 0 can be 0, others will be 1, like 01001 | 00001 = 01001 - ~ Operator:
for example, 8 = 00010000
-8 = ~8 + 1 = 11101111 + 00000001 = 11110000
~8 = 11101111 = 00010000 - 00000001 = 00010001 = |-9| = -9 - ^ Operater:
only 1 and 0, or 0 and 1 can be 1, others will be 0, like 01001 & 00001 = 01000 - << Operater:
move all to left, and append 0s at the end, like 01001 << 1 = 010010 - >> Operater:
move all to right, cut the last one, and append 0s at the start, like 01001 >> 2 = 00010
the sign doesn't move - <<< Operater:
same to << Operater - >>> Operater:
same to >> Operater, but the sign moves
Solution:
public int reverseBits(int n) {
int sum = 0;
for (int i = 31; i >= 0; i--) {
sum |= ((n & 1) << i); //use m as result, add the last bit to the (bits.length - i)th
n = n >>> 1; //move to next bit
}
return sum;
}
网友评论