Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
要求将一个无符号数进行二进制旋转,简单的位操作即可。。
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int result = 0; for (int i = 0; i < 32; i++){ result = result | (((n >> i & 1) << (31 - i))); } return result; } }
也可以优化一下。
public int reverseBits(int n) { if (n == 0) return 0; int result = 0; for (int i = 0; i < 32; i++) { result <<= 1; if ((n & 1) == 1) result++; n >>= 1; } return result; }