Solution by sha256pki


  • 0
    S

    A number is pallindrome if it reads same forward as well as backward.
    A problem is to determine if given number is pallindrome or not.
    One of the simplest and most intuitive way to do is to check if number reads same forward and backward.

    12321 - is pallindrome
    123321 - is pallidrome

    A way to solve this would be to compare most significant digit with least significant digit. If they're same, chop off the most and least significant digit and continue the test. If they're not same, then number is not pallindrome.

    A negative number is not pallindrome - it doesn't read same forward and backward.

            if x < 0:
                return False
    

    Compute how many digits are there in a number:

            ndigits = 0
            temp    = x
            while temp:
                ndigits += 1
                temp    = temp / 10
    

    At the end of above loop - ndigits will be number of digits in an input integer
    Now let's test for pallindrome. Check most significant with least significant, if two are different, return False, if two are same, then continue with the test -

            msp = 10**(ndigits-1)   # most significant place        
            while x:
                msd = x//msp # most significant digit
                lsd = x%10   # least significant digit
                if msd != lsd:
                    return False
                x = x % msp     # chop off most significant digit
                x = x // 10     # chop off least significant digit
                msp = msp//100  # account for previous chopping, adjust most significant place
                
            return True
    

    Combining all of the above below is final solution -

    class Solution(object):
        def isPalindrome(self, x):
            """
            :type x: int
            :rtype: bool
            """
            if x < 0:
                return False
            
            ndigits = 0
            temp    = x
            while temp:
                ndigits += 1
                temp    = temp / 10
            
            msp = 10**(ndigits-1)   # most significant place        
            while x:
                msd = x//msp # most significant digit
                lsd = x%10   # list significant digit
                if msd != lsd:
                    return False
                x = x % msp     # chop off most significant digit
                x = x // 10     # chop off list significant digit
                msp = msp//100  # account for previous chopping, adjust most significant place
                
            return True
    

    Time Complexity - O(d) where d is number of digits in an integer


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.