Leetcode 190. 颠倒二进制位 位运算/分治
·
原题链接:Leetcode 190. 颠倒二进制位

位运算:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int res=0;
for(int i=0;i<32;i++)
{
if((n>>i)&1) res|=(1<<(31-i));
}
return res;
}
};
分治:参考题解【负雪明烛】「循环」与「分治」解法
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
n = (n >> 16) | (n << 16);//低16位与高16位交换
n = ((n & 0xff00ff00 ) >> 8) | ((n & 0x00ff00ff) << 8);//每16位中低8位与高8位交换,f即1111
n = ((n & 0xf0f0f0f0 ) >> 4) | ((n & 0x0f0f0f0f) << 4);//每8位中高4位与低4位交换
n = ((n & 0xcccccccc ) >> 2) | ((n & 0x33333333) << 2);//每4位中高2位与低2位交换,c 1100 3 0011
n = ((n & 0xaaaaaaaa ) >> 1) | ((n & 0x55555555) << 1);//每2位中低1位与高1位交换,a 1010 5 0101
return n;
}
};
更多推荐
所有评论(0)