ที่นี่เราใช้ฟังก์ชัน inbuilt หลามที่แตกต่างกัน อันดับแรก เราใช้ bin() เพื่อแปลงตัวเลขเป็นเลขฐานสอง จากนั้นกลับรูปแบบไบนารีของสตริงและเปรียบเทียบกับต้นฉบับ หากตรงกัน ให้ palindrome ไม่เช่นนั้น
ตัวอย่าง
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