您的位置:首页 > 其它

Leetcode - Reverse Bits

2016-05-04 21:37 323 查看

Question

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).

Follow up

If this function is called many times, how would you optimize it?

Java Code

//版本一:使用字符串,得到原数值的二进制字符串,再进行反转和二进制解析
public int reverseBits(int n) {
String binaryStr = Integer.toBinaryString(n);//得到二进制形式字符串(无前导符0)
StringBuffer sb = new StringBuffer();
int add = 32 - binaryStr.length();
//用前导符0补全二进制形式字符串的若干高位
while(add-- > 0) sb.append("0");
//反转二进制形式字符串,再解析
return (int)Long.parseLong(sb.append(binaryStr).reverse().toString(), 2);
}

//版本二:使用位操作,依次取出二进制串的各个位,再构造反转二进制串
public int reverseBits2(int n) {
int i = 32;
int reverseNum = n & 1;//取出二进制表示的最低位
while(--i > 0) {
//反转数值左移一位,空出最低位来
reverseNum <<= 1;
//原数值右移一位,获取其最低位的值,填到反转数值的最低位
reverseNum |= (n >>>= 1) & 1;
}
return reverseNum;
}

//版本三:使用位操作,初始化一个列表,用于取出32位整数的各个二进制位,减少移位操作
public int reverseBits3(int n) {
int i = -1;
int reverseNum = 0;
while(++i < 16)
reverseNum |=  ((n & table[i]) << 31-2*i);

--i;
while(++i < 32)
reverseNum |=  ((n & table[i]) >>> 2*i-31);

return reverseNum;
}

final static int[] table = new int[]{
0x00000001,0x00000002,0x00000004,0x00000008,
0x00000010,0x00000020,0x00000040,0x00000080,
0x00000100,0x00000200,0x00000400,0x00000800,
0x00001000,0x00002000,0x00004000,0x00008000,
0x00010000,0x00020000,0x00040000,0x00080000,
0x00100000,0x00200000,0x00400000,0x00800000,
0x01000000,0x02000000,0x04000000,0x08000000,
0x10000000,0x20000000,0x40000000,0x80000000
};

//版本四:直接使用JDK中的二进制位反转函数Integer.reverse(),其源码如下
public int reverseBits4(int i) {
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode reverse bits