Complexity O(logN) and Memory O(1), A Different Solution.


  • 0
    L

    My solution: O(logN) complexity and O(1) memory.
    It is different to others to some extent.

    # Computation O(logn)
    # Memory O(1)
    # Accepted
    # This algorithm requires to measure the length of number which takes O(logn)
    
    class Solution(object):
        def isPalindrome(self, x):
            """
            :type x: int
            :rtype: bool
            """
            if x < 0:
                return False
            else:
                # Determine the length of number
                num_length = 0
                while (x - pow(10,num_length)) >= 0:
                    num_length += 1
                
                num = x
                i = 0
                while i < num_length/2:
                    last_digit = num % 10
                    first_digit = num / pow(10,num_length-1-i*2)
                    if last_digit != first_digit:
                        return False
                    else:
                        num = (num - first_digit * pow(10,num_length-1-i*2) - last_digit) / 10
                        i += 1
                
                return True
    
    
    

Log in to reply
 

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