您的位置:首页 > 其它

Leetcode: Reverse Bits

2015-03-14 07:06 239 查看
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?

Related problem: Reverse Integer


这道题不用我们自己去考虑怎么把int 转化为unsigned int,题目已经帮我们自动转化好了

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int i=0; i<32; i++) {
int bit = (n>>i) & 1;
res |= bit<<(31-i);
}
return res;
}
}


Q:如果该方法被大量调用,或者用于处理超大数据(Bulk data)时有什么优化方法?
A:这其实才是这道题的精髓,考察的大规模数据时算法最基本的优化方法。其实道理很简单,反复要用到的东西记下来就行了,所以我们用Map记录之前反转过的数字和结果。更好的优化方法是将其按照Byte分成4段存储,节省空间。参见这个帖子。(未深究)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: