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
廣告