Python中正整数的反向位

给定一个正整数和位的大小,将其所有位反转,并返回带有反转位的数字。

null

例如:

Input : n = 1, bitSize=32
Output : 2147483648  
On a machine with size of 
bit as 32. Reverse of 0....001 is
100....0.

Input : n = 2147483648, bitSize=32
Output : 1  

我们可以用Python快速解决这个问题。方法很简单,

  1. 使用 bin(num) 作用
  2. bin() 函数附加 0b 作为数字二进制表示法中的前缀,跳过二进制表示法的前两个字符,反转字符串的剩余部分。
  3. 正如我们所知,在内存中,一个数字的任何二进制表示都会在左起的最后一个设定位后填充前导零,这意味着我们需要追加 bitSize–len(反向位) 反转剩余字符串后的零数。
  4. 现在使用 int(字符串,基) 方法

int()方法如何工作?

int(字符串,基) 方法获取一个字符串和基数,以标识该字符串所指的是什么数字系统(二进制=2,heaxdecimal=16,八进制=8等),并相应地将字符串转换为十进制数字系统。例如int(’1010’,2)=10。

# Function to reverse bits of positive
# integer number
def reverseBits(num,bitSize):
# convert number into binary representation
# output will be like bin(10) = '0b10101'
binary = bin (num)
# skip first two characters of binary
# representation string and reverse
# remaining string and then append zeros
# after it. binary[-1:1:-1]  --> start
# from last character and reverse it until
# second last character from left
reverse = binary[ - 1 : 1 : - 1 ]
reverse = reverse + (bitSize - len (reverse)) * '0'
# converts reversed binary string into integer
print ( int (reverse, 2 ))
# Driver program
if __name__ = = "__main__" :
num = 1
bitSize = 32
reverseBits(num,bitSize)


输出:

2147483648
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享