Using Python, Reverse An Integer, And Tell If Palindrome
Solution 1:
defpalindrome(num):
returnstr(num) == str(num)[::-1]
Solution 2:
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):
def reverse(num):
rev =0while num > 0:
rev = (10*rev) + num%10
num //= 10return rev
Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):
defreverse(num):
returnint(str(num)[::-1])
Solution 3:
This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.
def reverse(i):
returnint(i!=0) and ((i%10)*(10**int(math.log(i,10))) + reverse(i//10))
def is_palindrome(i):
return i == reverse(i)
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.
Solution 4:
Long but readable:
defpalindrome(x):
a=""
x=str(x)
for i inrange(len(x),0,-1):
a+=x[i-1]
print a
if a==x:
returnTrueelse:
returnFalse
Solution 5:
defrevers(num):
rev = 0while num > 0:
rem = num % 10
rev = (rev * 10) + rem
num = num // 10return rev
Post a Comment for "Using Python, Reverse An Integer, And Tell If Palindrome"