将 n 视作一个长为 32 的二进制串,从低位往高位枚举 n 的每一位,将其倒序添加到翻转结果 rev 中。每枚举一位就将 n 右移一位,这样当前 n 的最低位就是我们要枚举的比特位。当 n 为 0 时即可结束循环。
1 2 3 4 5 6 7 8 9 10 11
publicclassSolution { // you need treat n as an unsigned value publicintreverseBits(int n) { intrev=0; for (inti=0; i < 32 && n != 0; i++) { rev |= (n & 1) << (31 - i); n >>>= 1; } return rev; } }
publicclassSolution { // you need treat n as an unsigned value privatestaticfinalintM1=0x55555555; // 01010101010101010101010101010101 privatestaticfinalintM2=0x33333333; // 00110011001100110011001100110011 privatestaticfinalintM4=0x0f0f0f0f; // 00001111000011110000111100001111 privatestaticfinalintM8=0x00ff00ff; // 00000000111111110000000011111111
publicintreverseBits(int n) { n = n >>> 1 & M1 | (n & M1) << 1; n = n >>> 2 & M2 | (n & M2) << 2; n = n >>> 4 & M4 | (n & M4) << 4; n = n >>> 8 & M8 | (n & M8) << 8; return n >>> 16 | n << 16; } }