Error with my code that checks if a number is a palindrome

97 Views Asked by At

This is my code that checks if a number is a palindrome.

class Solution(object):
    def isPalindrome(self, x):
        string = str(x)
        idx = 0
        # if the number is even; 
        if (x % 2) == 0:
            for i in range (1, len(string)/2 + 1):
                if string[i - 1] == string[len(string) - i]:
                    idx += 1 
            if idx == len(string)/2: 
                return True
        #if the number is odd: 
        else: 
            if len(string) > 2: 
                for i in range(1, (len(string)-1)/2 + 1):
                    if string[i - 1] == string[len(string) - i]:
                        idx += 1
                if idx == (len(string)-1)/2:
                    return True
            elif len(string) == 2: 
                if string[0] == string[1]: 
                    return True
            else: 
                return True

But, why doesn't my code work when x = 1000030001? My program thinks that 1000030001 is a palindrome. Can anybody tell me where my code is incorrect?

I already tried to plug in every value manually to debug, and it shows that it will return False, even though when I run the program it returns True.

2

There are 2 best solutions below

0
Arunbh Yashaswi On

The issue in regards to code is that you are checking if the number is even or not instead of the length of that number being even or odd.

you could simply do

class Solution():
    def isPalindrome(x):
        string = str(x)
        for i in range(len(string) // 2):
            if string[i] != string[-i - 1]:
                return False
        return True

and now if you run you will get False for 1000030001

0
Jacek Błocki On

What about this:

def is_palindrome(x):
    return str(x) == str(x)[::-1]