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).

二. 题目分析

题目的要求比较简单,输入一个32位的无符号整数,根据其二进制表示,输出与其二进制相对称的无符号整数。题目也给出了一个例子。

该题使用基本的位运算即可解决,当然网上也提出了一种很巧妙的方法,其中对于位运算有这样的一种方法,将数字的位按照整块整块的翻转,例如32位分成两块16位的数字,16位分成两个8位进行翻转,以此类推。

对于一个8bit数字abcdefgh来说,其处理过程如下:

abcdefgh -> efghabcd -> ghefcdab -> hgfedcba

进一步的论述,抄送网上的解释:

Remember how merge sort works? Let us use an example of n == 8 (one byte) to see how this works:

        01101001
       /        \    0110          1001
  /    \        /    \  01     10     10     01
 /\     /\     /\      /\ 0  1   1  0   1  0     0 1

The first step is to swap all odd and even bits. After that swap consecutive pairs of bits, and so on…

Therefore, only a total of log(n) operations are necessary.

The below code shows a specific case where n == 32, but it could be easily adapted to larger n‘s as well.

三. 示例代码

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t result = 0;
        if (n == result) return result;
        int index = 31; // 初始时n的最低位需要右移31位到最高位
        while (n)
        {
            result |= (n & 0x1) << index; // 取n的最低位,并右移到高位
            --index; // 右移位数,保持对称
            n >>= 1; 
        }
        return result;
    }
};
// 另一种巧妙的做法
/*
0x55555555 = 0101 0101 0101 0101 0101 0101 0101 0101
0xAAAAAAAA = 1010 1010 1010 1010 1010 1010 1010 1010
0x33333333 = 0011 0011 0011 0011 0011 0011 0011 0011
0xCCCCCCCC = 1100 1100 1100 1100 1100 1100 1100 1100
*/
class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t x = n; x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1); x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2); x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4); x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8); x = ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16); return x; } };

四. 小结

实现该题的要求不难,但是精彩的做法让人大开眼界。

你可能感兴趣的:(LeetCode,位运算,C++,算法,bit)