[LeetCode] C++: Simple Question-Bit Operation 190. Reverse Binary Bits

190. Reverse Binary Bits

Easy difficulty 256

Reverse the binary bits of a given 32-bit unsigned integer.

 

Example 1:

输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
     因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。

Example 2:

输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
     因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。

 

prompt:

  • Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both the input and output will be designated as signed integer types, and should not affect your implementation, because the internal binary representation is the same regardless of whether the integer is signed or unsigned.
  • In Java, the compiler uses two's complement notation to represent signed integers. Therefore, in  Example 2  above, the input represents a signed integer  -3and the output represents a signed integer  -1073741825.

 

Advanced :
If you call this function multiple times, how will you optimize your algorithm?

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t ret = 0, power = 31;
        while(n != 0){
            ret += (n & 1) << power;
            n = n >> 1;
            power -= 1;
        }
        return ret;
    }
};

I don’t know much about bit operations, so explain the code above:

n&1 is to take the last digit of n, and then shift the power digits to the left, that is, reverse it to the power+1 digit. Then n is shifted one bit to the right, that is, the last bit before it is removed, power--.

Loop until all the bits of n are reversed.

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113729700