Python 程序如何检查二进制表示是不是回文?
这里,我们用不同的 Python 内置函数。首先,我们使用 bin() 将数字转换为其二进制形式,然后反转字符串的二进制形式并比较与原先的情形,如果匹配,则为回文,否则不是回文。
示例
Input: 5 Output: palindrome
解释
5 的二进制表示是 101
反转它,结果为 101,然后比较,发现与原先的情形匹配。
因此它是一个回文。
算法
Palindromenumber(n) /* n is the number */ Step 1: input n Step 2: convert n into binary form. Step 3: skip the first two characters of a string. Step 4: them reverse the binary string and compare with originals. Step 5: if its match with originals then print Palindrome, otherwise not a palindrome.
示例代码
# To check if binary representation of a number is pallindrome or not defpalindromenumber(n): # convert number into binary bn_number = bin(n) # skip first two characters of string # Because bin function appends '0b' as # prefix in binary #representation of a number bn_number = bn_number[2:] # now reverse binary string and compare it with original if(bn_number == bn_number[-1::-1]): print(n," IS A PALINDROME NUMBER") else: print(n, "IS NOT A PALINDROME NUMBER") # Driver program if __name__ == "__main__": n=int(input("Enter Number ::>")) palindromenumber(n)
输出
Enter Number ::>10 10 IS NOT A PALINDROME NUMBER Enter Number ::>9 9 IS A PALINDROME NUMBER
广告