[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/
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[파이썬 알고리즘 인터뷰] 로그파일 재정렬 (0) | 2020.12.11 |
---|---|
[파이썬 알고리즘 인터뷰] 문자열 뒤집기 (0) | 2020.11.28 |
[파이썬알고리즘 인터뷰] 유효한 팰린드롬 구하기 (0) | 2020.11.28 |
[leetcode] 7. Reverse Integer (0) | 2020.11.11 |
[leetcode] 3. Longest Substring Without Repeating Characters (0) | 2020.11.02 |