Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?
def reverse(num):
s=len(num)
newnum=[None]*length
for i in num:
s=s-1
newnum[s]=i
return newnum
def palindrome(num):
a=str(num)
l=len(z)/2
if a[:1]==a[-1:][::-1]:
b=True
else:
b=False
I am having some trouble to write def main
.
Integer numbers don't have len().
Testing if a number is a palindrome is as simple as testing if the number is equal to its reverse (though if you want maximum efficiency you can just compare characters from both ends of the string until you reach the middle).
To find the reverse of an integer you can either do it the hard way (using mod % and integer division // to find each digit and construct the reverse number):
Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):
Long but readable:
I try to come out with this myself.
I used a list for this program, works with strings too.
This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.
It works for integer
i ≥ 0
.Note that
reverse(123) == reverse(1230) == 321
. This is not a problem, considering any nonzero integer that ends with 0 cannot be a palindrome anyway.Note also that complete reversal of the integer may of course not be necessary to determine if it's a palindrome. The reversal may be implemented so as to be aborted early if the number is determined to not be a palindrome.