参考题解
>>>:逻辑右移(符号位一起移动,高位补零)
时间复杂度: O ( log n ) O(\log{n}) O(logn)
空间复杂度: O ( 1 ) O(1) O(1)
public class Solution {
// private static final int M1 = 0x55555555; // 01010101010101010101010101010101
private static final int M1 = 0B01010101010101010101010101010101; // 01010101010101010101010101010101
private static final int M2 = 0x33333333; // 00110011001100110011001100110011
private static final int M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
private static final int M8 = 0x00ff00ff; // 00000000111111110000000011111111
public int reverseBits(int n)
{
// >>> 逻辑右移(符号位一起移动)
n = n >>> 1 & M1 | (n & M1) << 1;// 交换相邻 1 个
n = n >>> 2 & M2 | (n & M2) << 2;// 交换相邻 2 个
n = n >>> 4 & M4 | (n & M4) << 4;// 交换相邻 4 个
n = n >>> 8 & M8 | (n & M8) << 8;// 交换相邻 8 个
return n >>> 16 | n << 16;// 交换相邻的 16 个
}
}