检查二进制表示法在Python中是否为回文

给定一个整数“n”,编写一个Python函数,如果x的二进制表示形式为回文,则返回true,否则返回false。

null

例如:

Input : n = 9
Output : True
Binary representation of n=9 is 1001 which 
is palindrome as well.

Input : n = 10
Output : False
Binary representation of n=10 is 1010 which 
is not palindrome.

我们有解决这个问题的现有方案,请参考 检查数字的二进制表示是否为回文 链接我们可以很快用python解决这个问题。方法很简单,

  1. 使用 bin(num) 功能。
  2. 现在反转数字的二进制表示字符串,并将其与原始二进制表示字符串进行比较,如果两者相等,则意味着数字的二进制表示是苍白的,否则就不是。

注: 我们可以使用另一种方法 检查字符串是否为回文 .

# Function to check if binary representation of
# a number is pallindrome or not
def binaryPallindrome(num):
# convert number into binary
binary = bin (num)
# skip first two characters of string
# because bin function appends '0b' as
# prefix in binary representation of
# a number
binary = binary[ 2 :]
# now reverse binary string and compare
# it with original
return binary = = binary[ - 1 :: - 1 ]
# Driver program
if __name__ = = "__main__" :
num = 9
print binaryPallindrome(num)


输出:

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