python 二进制数字
A positive number or string is said to be a palindrome if the reverse of the number or string is equal to the given number or string. For example, 132231 is a palindrome but 13243 is not.
如果数字或字符串的倒数等于给定的数字或字符串,则将正数或字符串称为回文 。 例如, 132231是回文,而13243不是 。
In this problem, a number will be given by the user and we have to convert it into a binary number and after this, we will check the binary representation is a palindrome or not. Before going to do the given task, we will learn how to convert a number into a binary number.
在这个问题中,用户将给出一个数字,我们必须将其转换为二进制数,然后,我们将检查二进制表示形式是否为回文。 在执行给定任务之前,我们将学习如何将数字转换为二进制数字。
Python program to convert a given decimal number (P) to binary number
Python程序将给定的十进制数(P)转换为二进制数
# input the number
P=int(input('Enter a number: '))
# convert into binary number
s=int(bin(P)[2:])
# printing the result
print("The binary representation of number:", s)
Output
输出量
RUN 1:
Enter a number: 17
The binary representation of number: 10001
RUN 2:
Enter a number: 100
The binary representation of number: 1100100
As we have learned how to convert a decimal number into a binary number in the above program and the binary representation of 90 is not a palindrome and this is our main task to check palindrome using Python. Now, we can easily solve it. So, let’s start writing the program to check the binary representation of the given number is a palindrome or not in Python.
正如我们已经了解了如何在上述程序中将十进制数转换为二进制数,并且90的二进制表示形式不是回文,这是我们使用Python检查回文的主要任务。 现在,我们可以轻松解决它。 因此,让我们开始编写程序以检查给定数字的二进制表示形式是否是回文,而在Python中则不是。
Program:
程序:
# input the number
P=int(input('Enter a number: '))
# converting to binary
s=int(bin(P)[2:])
# reversing the binary
r=str(s)[::-1]
# checking the palindrome
if int(r)==s:
print("The binary representation of the number is a palindrome.")
else:
print("The binary representation of the number is not a palindrome.")
Output
输出量
RUN 1:
Enter a number: 27
The binary representation of the number is a palindrome.
RUN 2:
Enter a number: 100
The binary representation of the number is not a palindrome.
In Python, str(P)[::-1] is used to reverse a number P which is a property of slicing.
在Python中, str(P)[::-1]用于反转数字P ,它是slicing的属性。
python 二进制数字