문제
주어진 숫자가 뒤집었을때도 같은 숫자면 True, 아니면 False반환
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
내 풀이
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return list(reversed(str(x))) == list(str(x))
# Runtime: 104 ms, faster than 43.79% of Python online submissions for Palindrome Number.
# Memory Usage: 13.3 MB, less than 85.23% of Python online submissions for Palindrome Number.
return str(x) == str(x)[::-1]
# Runtime: 66 ms, faster than 84.25% of Python online submissions for Palindrome Number.
# Memory Usage: 13.5 MB, less than 35.99% of Python online submissions for Palindrome Number.
1번
reversed를 활용하기 위해 x를 문자열로 바꾸고 reversed함수를 활용했는데 스트링을 reversed하면 거꾸로 된 스트링이 반환되는 게 아니라 reversed object가 반환된다. 그래서 이걸 다시 리스트로 바꾸고, 비교를 위해 스트링으로 바꾼 x를 리스트로 바꿔서 비교를 했다.
2번
스트링을 인덱스 활용해서 거꾸로 돌릴 수 있어서 스트링으로 바꾼 x랑 그걸 거꾸로 돌린거랑 비교해서 바로 리턴했다.
다른풀이1
class Solution(object):
def isPalindrome(self, x):
if x<0:
return False
inputNum = x
newNum = 0
while x>0:
newNum = newNum * 10 + x%10
x = x//10
return newNum == inputNum
# Runtime: 129 ms, faster than 20.48% of Python online submissions for Palindrome Number.
# Memory Usage: 13.2 MB, less than 85.27% of Python online submissions for Palindrome Number.
수학적으로 접근한 풀이.
x가 0보다 작으면 무조건 False니까 처음에 if문으로 걸러주고
x값을 따로 inputNum에 저장하고 나서 x를 뒤집은 수를 만드는 작업을 했다. print로 반복문을 돌때마다 찍어보면
# x = 123454321일때
newNum:1, x:12345432
newNum:12, x:1234543
newNum:123, x:123454
newNum:1234, x:12345
newNum:12345, x:1234
newNum:123454, x:123
newNum:1234543, x:12
newNum:12345432, x:1
newNum:123454321, x:0
이렇게 나온다. 그래서 newNum과 아까 저장해둔 inputNum을 비교한 값을 리턴
다른풀이1-1
if x < 0 or (x > 0 and x%10 == 0): # if x is negative, return False. if x is positive and last digit is 0, that also cannot form a palindrome, return False.
return False
result = 0
while x > result:
result = result * 10 + x % 10
x = x // 10
return True if (x == result or x == result // 10) else False
# Runtime: 106 ms, faster than 41.91% of Python online submissions for Palindrome Number.
# Memory Usage: 13.1 MB, less than 96.99% of Python online submissions for Palindrome Number.
위와 같은 방법인데 처음에 계산을 하지 않고 False로 바로 넘어가는 경우를 한가지 더 처리해줬고
반복문을 위 방법의 반만 돌고 답을 찾을 수 있는 방법.
반만 돈 상태에서 둘을 비교해서 같으면 완전히 거꾸로 다 돌렸을때도 같은 값이니까
ex) 123454321 -> 하나씩 빼서 거꾸로 만들다가 1234 54321 일때 비교하면 나머지 값을 거꾸로 다 돌리기 전에 판단가능
(자릿수가 홀수일 경우에 대비해서 true일 경우를 두가지로 나눴다.)
x = 123454321일때 print를 찍어보면
x: 12345432, result: 1
x: 1234543, result: 12
x: 123454, result: 123
x: 12345, result: 1234
x: 1234, result: 12345
이만큼만 찍히고 바로 ture를 리턴한다 그래서 위 방법보다는 빠르게 결과가 나온다.
'TIL' 카테고리의 다른 글
node.js | express, TypeORM 적용한 CRUD API만들기 - 1 db(dbmate) (0) | 2022.10.02 |
---|---|
node.js | TypeORM 적용하기 (0) | 2022.10.01 |
node.js | 인스타그램: 데이터베이스 구축 (0) | 2022.09.27 |
node.js | express로 서버 만들기 - 게시글 등록, 목록조회(DB x) (0) | 2022.09.27 |
node.js | express로 서버 만들기 - 회원가입 엔드포인트 만들기(DB x) (0) | 2022.09.26 |