Python 程序如何反转一个正整数的二进制位?


首先使用 bin() 函数将数字转换为二进制。然后跳过二进制表示的前两个字符,因为 bin() 会将一个数字的二进制表示中作为前缀添加 0b,并反转剩余部分。同时从右向左从倒数第二个字符开始逐个字符进行反转。将反转后的二进制字符串转换为整数。

算法

integernumber(n,bit_size)
/* n is the number and bit_size is the bitsize  */
Step 1: first convert number into binary .
Step 2: skip the first two characters of binary representation string and reverse.
Step 3: remaining string and then append 0’s after it.
Step 4: from the last character and reverse it until second last character from the left.
Step 5: converts reversed binary string into an integer.

示例代码

# Python Program reverse bits of positive integer number
defintegernumber(n,bit_size):
   bin_number = bin(n)
   reverse_number = bin_number[-1:1:-1]
   reverse_number = reverse_number + (bit_size - len(reverse_number))*'0'
   print ("Reverse Bits ::>",int(reverse_number,2))
# Driver program
if __name__ == "__main__":
   n = int(input("Enter Number ::>"))
   bit_size = int(input("Enter Bit Size ::>")) 
   integernumber(n,bit_size)

输出

Enter Number ::>1
Enter Bit Size ::>32
Reverse Bits ::> 2147483648

Enter Number ::>2147483648
Enter Bit Size ::>32
Reverse Bits ::> 1

更新时间:2019 年 7 月 30 日

2K+ 浏览量

开始你的 职业生涯

完成课程并获得认证

开始
广告