python 二进制数字_在Python中检查给定数字的二进制表示形式是否是回文

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的属性。

翻译自: https://www.includehelp.com/python/check-whether-the-binary-representation-of-a-given-number-is-a-palindrome-or-not.aspx

python 二进制数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值