YXH
YXH

Reputation: 401

Using Python, reverse an integer, and tell if palindrome

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.

Upvotes: 18

Views: 100852

Answers (14)

CSmith
CSmith

Reputation: 33

def pal_num(num):
    if num<0:
        print(False)
    elif num == int(str(num)[::-1]):
        print(True)
    else:
        print(False)

This example quickly takes care of the negative number edge case

Upvotes: 0

rashedcs
rashedcs

Reputation: 3725

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

Upvotes: 1

Rupesh Bagool
Rupesh Bagool

Reputation: 11

Reverse an integer and determine if it is a palindrome:

  1. Convert integer to string.
  2. Use reverse function to reverse the string and join it.
  3. Check if reversed number = original number with if else condition.

See code:

number = 1221

reverse = ''.join(reversed(str(number)))

print(reverse)

if (int(reverse) == number):
    print("number is Palindrome")
else:
    print("number is not Palindrome")

Upvotes: 1

Here is my solution.

z=input('input number')
if int(z) == int(str(z)[::-1]):
    print('The number is palindrome')
else:
    print('The number is not palindrome')

Upvotes: 0

Shehreen Khan
Shehreen Khan

Reputation: 75

t=int(input("enter nos of test cases= "))
while t>0:
    n=int(input("enter number="))
    rev=0
    while n>0:
        digit=n%10
        rev=rev*10+digit
        n=n//10
    print(rev)
    t-=1

Upvotes: 0

casillas
casillas

Reputation: 16813

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

Upvotes: 0

elon007
elon007

Reputation: 11

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

Upvotes: 1

Asclepius
Asclepius

Reputation: 63453

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.

Upvotes: 1

Devzzone
Devzzone

Reputation: 27

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

Upvotes: 0

pedrosorio
pedrosorio

Reputation: 870

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])

Upvotes: 20

Peter Hull
Peter Hull

Reputation: 769

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

Upvotes: 61

ankit bansal
ankit bansal

Reputation: 1

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"

Upvotes: -2

Ryan
Ryan

Reputation: 35

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='')

Upvotes: 0

blackstreet23
blackstreet23

Reputation: 1

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))

Upvotes: -2

Related Questions