Using Python, reverse an integer, and tell if pali

2019-01-14 17:28发布

问题:

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.

回答1:

def palindrome(num):
    return str(num) == str(num)[::-1]


回答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 = 0
  while num > 0:
    rev = (10*rev) + num%10
    num //= 10
  return 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):

def reverse(num):
  return int(str(num)[::-1])


回答3:

This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.

def reverse(i):
    return int(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.



回答4:

Long but readable:

def palindrome(x):
    a=""
    x=str(x)
    for i in range(len(x),0,-1):
        a+=x[i-1]
        print a
    if a==x:
        return True
    else:
        return False


回答5:

def revers(num): 
  rev = 0    
  while(num > 0):    
      rem = num %10    
      rev = (rev *10) + rem    
      num = num //10    

  return num


回答6:

I used a list for this program, works with strings too.

print('Enter Something')
a = list(input())
for i in range ((len(a)),0,-1):
   print (a[i-1],end='')


回答7:

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 ":("


回答8:

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


回答9:

I try to come out with this myself.

def number():

    n = int(input("Enter a number: "))
    return n

def reverse(n):


    total = ""
    while n > 0:
        a = n % 10

        n//= 10


        total+= str(a)

    return total


def palindrome (n):

    total = 0
    while n > 0:
        a = n % 10

        n//= 10


        total+= a

    if total == n:
        x = "This number has a palindrome"

    else:
        x = ""

    return x

n = number()
print (reverse(n))
print (palindrome(n))


回答10:

original = raw_input("Enter a no = ")   #original = number entered by user
rev = original[::-1]     #rev = reverse of original by useing scope resolution 
print 'rev of original no =',rev
if original == rev:
    print "no's are equal"
else:
    print "no's are not equal"