Palindrome number in python (leetcode)

Viewed 50
class Solution:
    def isPalindrome(self, x: int) -> bool:
        # If x is a negative number it is not a palindrome
        # If x % 10 = 0, in order for it to be a palindrome the first digit should also be 0
        if x < 0 and x%10 == 0):   
            return False

        reversedNum = 0
        while x > reversedNum:
            reversedNum = reversedNum * 10 + x % 10
            x = x // 10

        # If x is equal to reversed number then it is a palindrome
        # If x has odd number of digits, dicard the middle digit before comparing with x
        # Example, if x = 23132, at the end of for loop x = 23 and reversedNum = 231
        # So, reversedNum/10 = 23, which is equal to x
        return True if (x == reversedNum or x == reversedNum // 10) else False

This is my code which is giving wrong output for 660, Expected output : False My output : True

Can someone tell me how to correct this.

3 Answers
reversedNum = 0
Num=x
while x > 0:
    reversedNum = reversedNum * 10 + x % 10
    x = x // 10

return True if (Num == reversedNum) else False

You don't really need an explicit check for a negative number because the while loop (in the following code) will not be entered and the return value will be an equality test between zero and some negative number - which is obviously False.

So:

def ispalindrome(x):
    n = x
    r = 0
    while n > 0:
        r *= 10
        r += n % 10
        n //= 10
    return r == x

if you convert the number to a string is very simple. you only need to check that the string written backwards is the same

def ispalindrome(x):
    return str(x) == str(x)[::-1]
ispalindrome(23132)
>>> True
Related