您的位置:首页 > 其它

[LeetCode]Reverse Bits

2016-12-13 20:15 22 查看

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?

本题难度Easy。有2种算法分别是: 位运算 和 分段调换法

1、位运算

复杂度

时间 O(N) 空间 O(1)

思路

取出
n
的最低位
b
,将
ans
左移后将
b
赋给
ans
的最低位,然后将
n
右移。

注意

第8行我开始写成
ans=ans<<1+(n&1);
,这样得到的结果是错误的,原因就在于
<<
优先级低于
+
,实际上它相当于
ans=ans<<(1+(n&1));
,正确的写法应该是
ans=(ans<<1)+(n&1);


代码

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
//require
int ans=0;
//invariant
for(int i=0;i<32;i++){
ans=ans<<1|(n&1);
n>>=1;
}
//ensure
return ans;
}
}


2、分段调换法

复杂度

时间 O(N) 空间 O(1)

思路

试想一下,我们还有没有更好的方案呢,答案当时是肯定的。在斯坦福的这篇文章(http://graphics.stanford.edu/~seander/bithacks.html)里面介绍了众多有关位操作的奇思妙想,有些方法的确让人称赞,其中对于位翻转有这样的一种方法,将数字的位按照整块整块的翻转,例如32位分成两块16位的数字,16位分成两个8位进行翻转,这样以此类推知道只有一位。

例如对于一个8位数字
abcdefgh
来讲,处理的过程如下:

abcdefgh -> efghabcd -> ghefcdab -> hgfedcba

注意

这里的
n
是有符号数,因此右移要使用无符号右移
>>>
而不可用
>>


代码

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
//invariant
n = (n >>> 16) | (n << 16);
n = ((n & 0xff00ff00) >>> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >>> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >>> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >>> 1) | ((n & 0x55555555) << 1);
//ensure
return n;
}
}


Follow up

Q:如果该方法被大量调用,或者用于处理超大数据(Bulk data)时有什么优化方法?

A:这其实才是这道题的精髓,考察的大规模数据时算法最基本的优化方法。其实道理很简单,反复要用到的东西记下来就行了,所以我们用Map记录之前反转过的数字和结果。更好的优化方法是将其按照Byte分成4段存储,节省空间。参见这个帖子

代码

public class Solution {
// cache
private final Map<Byte, Integer> cache = new HashMap<Byte, Integer>();
public int reverseBits(int n) {
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) // convert int into 4 bytes
bytes[i] = (byte)((n >>> 8*i) & 0xFF);
int result = 0;
for (int i = 0; i < 4; i++) {
result <<= 8;
result += reverseByte(bytes[i]); // reverse per byte
}
return result;
}

private int reverseByte(byte b) {
Integer value = cache.get(b); // first look up from cache
if (value != null)
return value;
value = 0;
// reverse by bit
for (int i = 0; i < 8; i++) {
value <<= 1;
value += ((b >>> i) & 1);
}
cache.put(b, value);
return value;
}
}


参考

[Leetcode] Reverse Bits 反转位
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode