Using Python, reverse an integer, and tell if pali

2019-01-14 17:15发布

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.

10条回答
淡お忘
2楼-- · 2019-01-14 17:52
def palindrome(num):
    return str(num) == str(num)[::-1]
查看更多
爷的心禁止访问
3楼-- · 2019-01-14 17:53

This code converts int to String and then checks if the string is pallindrome. The advantage is that it is fast, the disadvantage being that it converts int to String thereby compromising with the perfect solution to question.

It handles negative int as well.

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        s = str(x)
        if x >=0 :
            if s == s[::-1]:
                return True
            else:
                return False
        else:
            return False
查看更多
Juvenile、少年°
4楼-- · 2019-01-14 17:54
import math

a = raw_input("Enter number:")
n = -1

reverse = 0    
for i in a:
        n += 1
        digit = math.pow(10,n)
        reverse = int(i)*digit + reverse

print int(reverse)  

if int(reverse) == int(a):
        print "Palindrome"
else:
        print ":("
查看更多
你好瞎i
5楼-- · 2019-01-14 17:57
def revers(num): 
  rev = 0    
  while(num > 0):    
      rem = num %10    
      rev = (rev *10) + rem    
      num = num //10    

  return num
查看更多
登录 后发表回答