My accepted python code - one additional space is used. Is it okay?


  • 4
    L
    class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        if x<0:
            return False 
        flag=1
        while x/flag>=10:
            flag=flag*10
        if flag==1:
            return True
        else:
            while flag>=1:
                x=int((x-(x%10)*flag)/10)
                flag=flag/100
            if x==0:
                return True
            else:
                return False
    

    this piece of code works in this way: 1st use flag to record how many digit this integer have. Then iteratively calculate int((x-(x%10)*flag)/10). If the integer is palindrome, the number of digit will reduce by 2 and finally x would become 0.

    However, an additional memory space for flag is used here, though the answer got accepted. Any suggestions on bettering this piece of code would be appreciated.

    Thanks for your attention.


  • 0
    P

    My solution:

    class Solution(object):
    def isPalindrome(self, x):
    """
    :type x: int
    :rtype: bool
    """
    x = str(x)
    if x == x[::-1]:
    return True
    else:
    return False


  • 0
    S

    Number should not be converted to string


  • 0
    M

    @PunamShaw I did the same way but I am not sure if is considered as a good practice to convert integer to string.


  • 0
    T

    class Solution(object):
    def isPalindrome(self, x):
    """
    :type x: int
    :rtype: bool
    """
    n=x
    y=0
    if n<0:
    return False
    while n>0:
    a=n%10

            n=n//10
           
            if n>=0:
                y=y*10+a
                
               
        return y==x

Log in to reply
 

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