您的位置:首页 > 其它

leetcode - Reverse Bits

2015-05-12 17:43 99 查看
leetcode - Reverse Bits

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

class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int bits[32];
for(int i=0; i<32; i++)
bits[i]=0;
int j = 0;
uint32_t sum = 0;
while(n!=0){
int tp = n%2;
n /= 2;
bits[j] = tp;
j++;
}
for(int i=31, k=0; i>=0; i--, k++){
sum += pow(2,k)*bits[i];
}
return sum;
}
};


题目不难,但是如何optimize? 显然应该是用位操作。自己的这个方法太业余了。
http://www.bubuko.com/infodetail-670143.html 这个文章里讲了非常好的方法,一个是位操作,每次移位直接保存,然后输出即可。

当然,位操作必须要熟悉,与1相与得最后一位,与1(0)相或,将某一位设置为1(0); 每次都对最后一位操作,操作完之后左右移位,直到32位全部操作完。

example:

class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t  answer;
uint32_t int i;

answer = 0;

/*把一个unsigned int 数字1一直左移,直到它变成全0的时候,也就得到了该机器内unsigned int的长度*/
for (i = 1; i != 0; i <<= 1)
{
answer <<= 1;
if (value & 1) { answer |= 1; }
value >>= 1;
}

return answer;
}
};


然而更好的办法是一种二分翻转的办法 (自己起的名字。。。)


http://graphics.stanford.edu/~seander/bithacks.html

在斯坦福的这篇文章里面介绍了众多有关位操作的奇思妙想,有些方法的确让人称赞,其中对于位翻转有这样的一种方法,将数字的位按照整块整块的翻转,例如32位分成两块16位的数字,16位分成两个8位进行翻转,这样以此类推知道只有一位。

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

abcdefgh -> efghabcd -> ghefcdab -> hgfedcba

class Solution {
public:
uint32_t reverseBits(uint32_t n) {
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);
return n;
}
};


这种方法的效率为O(log sizeof(int))。


from: http://www.bubuko.com/infodetail-670143.html
amazing!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: