Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Envoy
- 알고리즘
- LongestPalindromicSubstring
- 아마조니언
- 파이썬
- Dynamic Programmin
- technical debt
- 블린이
- BFS
- 삼성역량테스트
- 기술적 채무
- 그거봤어?
- 나는 아마존에서 미래를 다녔다
- No Rules Rules
- 삼성인 아마조니언 되다
- mysql #numa #swap #memory
- 김태강
- 트리
- Python
- 리트코드
- minimum path sum
- list of list
- Unique Paths
- 리스트의 리스트
- 프로그래머스
- 독후감
- 동적 프로그래밍
- leetcode
- 규칙없음
- 와썹맨
Archives
- Today
- Total
개발자가 되고 싶은 준개발자
[LeetCode] 7. Reverse Integer 파이썬 코드 본문
문제
7. Reverse Integer [Easy]
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1: Input: x = 123 Output: 321 |
Example 2: Input: x = -123 Output: -321 |
Example 3: Input: x = 120 Output: 21 |
Example 4: Input: x = 0 Output: 0 |
코드
이 문제는 요즘의 손코딩 문제(?)스러운 것 같다.. 문제 자체는 난이도가 높지 않지만, 스스로 예외 케이스를 생각해서 빠짐없이 꼼꼼히 짜는 것이 포인트이다.
주요 포인트
1) 부호
2) 0이 숫자 끝에 붙은 경우 (여러 개인 경우도 처리!)
3) 범위 체크! (파이썬에서 제곱은 2**n으로 표시. 2^n이 아니라!)
class Solution:
def reverse(self, x: int) -> int:
x = str(x)
# reverse string
x = x[::-1]
# if reversed integer starts with consecutive 0
# and is not 0, cut off front part
if x[0] == '0' and x != '0':
for i in range(len(x)):
if x[i] != '0':
x = x[i:]
break
# move sign bit to first digit if exists
if not x[-1].isdigit():
if x[-1] == '-':
x = int(x[0:-1])*(-1)
else:
x = int(x[0:-1])
else:
x = int(x)
# range check
left_range = -1*2**31
right_range = 2**31-1
if x < left_range or x>right_range:
return 0
return x
결과
'알고리즘 공부 > LeetCode' 카테고리의 다른 글
[LeetCode] 16. 3Sum Closest 파이썬 코드 (0) | 2021.05.29 |
---|---|
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 풀이 및 코드 (0) | 2021.03.07 |
[LeetCode] 230. Kth Smallest Element in a BST 문제 및 풀이 코드 (0) | 2021.03.07 |
[LeetCode] 98. Validate Binary Search Tree 풀이 및 코드 (0) | 2021.02.27 |
[LeetCode] 100. Same Tree 풀이 및 코드 (1) | 2020.09.26 |