publicclassSolution { // you need treat n as an unsigned value publicintreverseBits(int n) { for (inti=0; i < 16; i++) { intlowBit= (n >>> i) & 1; inthighBit= (n >>> (31 - i)) & 1; if (lowBit != highBit) { if (lowBit == 0) { // 高位改为 0, 低位改为 1 n &= ~(1 << (31 - i)); n |= (1 << i); } else { // 高位改为 1, 低位改为 0 n |= (1 << (31 - i)); n &= ~(1 << i); } } }
return n; } }
循环
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution { // you need treat n as an unsigned value publicintreverseBits(int n) { intres=0;
for (inti=0; i < 32 && n != 0; i++) { res |= (n & 1) << (31 - i); n >>>= 1; }
return res; } }
分治
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassSolution { // you need treat n as an unsigned value privatestaticfinalintB1=0b01010101010101010101010101010101; privatestaticfinalintB2=0b00110011001100110011001100110011; privatestaticfinalintB4=0b00001111000011110000111100001111; privatestaticfinalintB8=0b00000000111111110000000011111111;