[leetcode] 9. Palindrome Number

2020. 11. 11. 10:11노트/Algorithm : 알고리즘

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Follow up: Could you solve it without converting the integer to a string?

 

 

 

1. str 으로 바꿔서 한글자씩 분리해서 푸는 방법

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if -pow(2,31) <= x <= pow(2,31)-1 :
            x = str(x)
            y =''.join(reversed(str(x)))
            if x == y :
                return True
            else :
                return False
        else:
            return None

 

2. int 인 상태에서 한자리씩 숫자를 분리해서 푸는 방법

class Solution(object):
    def isPalindrome(x):
        """
        :type x: int
        :rtype: bool
        """
        if -pow(2,31) <= x <= pow(2,31)-1 :
            li = []
            input_ = x
            for i in range(len(str(x))):
                y=divmod(x,10)[1] # 3 
                li.insert(i,y)
                x=divmod(x,10)[0] # 12 
            y = [''.join(str(li[i]) for i in range(len(li)))]
            y = int(y[0])
            if input_ == y:
                return True
            else :
                return False
        else:
            return None

 

3. 리스트 inverse 기호를 이용해서 푸는 방법 

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

 

 

 

출처 

leetcode.com/problems/palindrome-number/

 

Palindrome Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com