Algorithm of the Day----190. Reversing Binary Bits----2023/1/4

1. Question description

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

hint:

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

Source: LeetCode
Link: https://leetcode.cn/problems/reverse-bits
The copyright belongs to LeetCode Network. For commercial reprinting, please contact the official authorizer. For non-commercial reprinting, please indicate the source.

2. Example

示例 1:

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

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

hint:

The input is a binary string of length 32

Source: LeetCode
Link: https://leetcode.cn/problems/reverse-bits
The copyright belongs to LeetCode Network. For commercial reprinting, please contact the official authorizer. For non-commercial reprinting, please indicate the source.

3. Ideas

The incoming number is traversed and divided by 2, then multiplied by the corresponding module length of the bit, and the value of each bit is accumulated to achieve flipping. It is a really stupid operation.

4. Problems encountered

none

5. Specific implementation code

func reverseBits(num uint32) uint32 {
    
    
    var target uint32
    var changeNum uint32
    changeNum = 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2
    for i:=0;i<32;i++{
    
    
        target = target + num %2* changeNum
        changeNum /= 2
        num /= 2
    }
    return target
}

6. Official solution

const (
    m1 = 0x55555555 // 01010101010101010101010101010101
    m2 = 0x33333333 // 00110011001100110011001100110011
    m4 = 0x0f0f0f0f // 00001111000011110000111100001111
    m8 = 0x00ff00ff // 00000000111111110000000011111111
)

func reverseBits(n uint32) uint32 {
    
    
    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
}

Bitwise divide and conquer

7 Source of question

Link: link


Official 666, another day of learning that did not let you down~ ------swrici

Guess you like

Origin blog.csdn.net/Srwici/article/details/128556285