欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Leetcode】190. Reverse Bits(二进制数反转)

程序员文章站 2022-07-14 23:35:40
...

Reverse bits of a given 32 bits unsigned integer.

 

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10101111110010110010011101101001.

题目大意:

给出一个二进制数,我们需要输出这二进制数的反转。

解题思路:

我们预设4位的二进制数的反转结果。

每次从n中取出四位,具体运算为XXXXXXXXXXXXXXX&0000000001111

找出对应的转换结果

与ans进行或操作,并且让ans<<4

class Solution {
char nums[16] = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}; // 预设4位数值反转之后所得到的结果
public:
    uint32_t reverseBits(uint32_t n) {
        // 每四位转换一次
        uint32_t ans = 0;
        uint32_t tmp = 0xF;
        for(int i=0;i<8;i++){
            ans <<= 4;
            int nn = tmp&n;
            ans |= nums[nn];
            n >>= 4;
        }
        return ans;
    }
};

 

相关标签: 二进制数