简体   繁体   English

使用 Python 反转数字中的位

[英]Reverse Bits in a Number Using Python

This question relates to the leetcode question to reverse bits of a 32 bits unsigned integer.这个问题与 leetcode问题有关,以反转 32 位无符号 integer 的位。

I tried the following code:我尝试了以下代码:

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
    
        result = 0
        BITMASK = 1

        for i in range(32):

            temp = n & BITMASK

            result = result | temp

            n = n >> 1
            
            result = result << 1

        return result

The strategy I was trying is to bitwise AND the last bit of the number with 1, then bitwise OR it with the result.我尝试的策略是将数字的最后一位与 1 按位与,然后将其与结果按位或。 The number is then right shifted by 1 to drop last bit, and the result is left shifted to make room for the next bit result.然后将该数字右移 1 以删除最后一位,并将结果左移以为下一位结果腾出空间。 The code doesn't generate the correct result.该代码不会生成正确的结果。 Can someone help me understand how to fix this code?有人可以帮助我了解如何修复此代码吗? Thanks.谢谢。

Try this尝试这个

class Solution:
    def reverseBits(self, n: int) -> int:
        bitmask = 1
        result = 0
        
        for i in range(31):
            temp = n & bitmask
            result = result | temp
            n = n>>1
            result = result<<1

        temp = n & bitmask
        result = result | temp
        return result

The main thing is that, when your code runs 32 times then at last it again shifts the result which gives the error, we need to run the code 31 times and last step of AND and OR keep it outside of the loop.主要的是,当您的代码运行 32 次时,最后它再次移动导致错误的结果,我们需要运行代码 31 次,最后一步 AND 和 OR 将其保持在循环之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM