颠倒二进制位

我的思路:32位,循环32次,从地位到高位枚举。
uint32_t reverseBits(uint32_t n) {
uint32_t mask = 1;
uint32_t res = 0;
for(int i=0;i<32;i++)
{
if((n & mask) != 0)
{
res <<=1;
res +=1;
}
else{
res<<=1;
}
mask<<=1;
}
return res;
}
官方题解:位运算分治(真的没想到)
若要翻转一个二进制串,可以将其均分成左右两部分,对每部分递归执行翻转操作,然后将左半部分拼在右半部分的后面,即完成了翻转。
由于左右两部分的计算方式是相似的,利用位掩码和位移运算,我们可以自底向上地完成这一分治流程。
const uint32_t M1 = 0x55555555; // 01010101010101010101010101010101
const uint32_t M2 = 0x33333333; // 00110011001100110011001100110011
const uint32_t M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
const uint32_t M8 = 0x00ff00ff; // 00000000111111110000000011111111
uint32_t reverseBits(uint32_t n) {
n = n >> 1 & M1 | (n & M1) << 1;
n = n >> 2 & M2 | (n & M2) << 2;
n = n >> 4 & M4 | (n & M4) << 4;
n = n >> 8 & M8 | (n & M8) << 8;
return n >> 16 | n << 16;
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reverse-bits/solution/dian-dao-er-jin-zhi-wei-by-leetcode-solu-yhxz/

浙公网安备 33010602011771号