Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để kiểm tra xem biểu diễn nhị phân có phải là palindrome không?

Ở đây chúng tôi sử dụng chức năng sẵn có của python khác nhau. Đầu tiên, chúng tôi sử dụng bin () để chuyển đổi số thành số nhị phân của nó, sau đó đảo ngược dạng nhị phân của chuỗi và so sánh với số gốc, nếu khớp thì palindrome ngược lại thì không.

Ví dụ

Input: 5
Output: palindrome

Giải thích

Biểu diễn nhị phân của 5 là 101

Đảo ngược nó và kết quả là 101, sau đó so sánh và kết quả khớp của nó với bản gốc.

Vì vậy, palindrome của nó

Thuật toán

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.

Mã mẫu

# 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)

Đầu ra

Enter Number ::>10
10 IS NOT A PALINDROME NUMBER
Enter Number ::>9
9 IS A PALINDROME NUMBER