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 | 29 | 30 |
31 |
Tags
- easy
- binary search
- 문자열
- sorting
- Python
- Medium
- list
- DP
- leetcode
- Depth-first Search
- backtracking
- Array
- 중간
- binary tree
- linked list
- 재귀
- recursive
- 리트코드
- matrix
- dfs
- two pointers
- Binary
- tree
- string
- hash table
- math
- 쉬움
- HashTable
- 미디움
- 이진트리
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 7(Reverse Integer, Python) 본문
1. 문제 링크
Reverse Integer - LeetCode
Can you solve this real interview question? Reverse Integer - 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 envir
leetcode.com
2. 문제 설명
- 부호가 있는 32bit 정수가 주어졌을 때, 앞뒤 순서를 바꾸어 반환
- 단, singed 32bit 정수의 범위인 [-231, 231 -1] 벗어나면 0 반환
- 예시1) 123이면 321 반환
- 예시2) -123이면 -321 반환
- 예시3) 120이면 21 반환
3. 처음 풀이
- 그냥 단순히 0 이상이면 str() 이용하여 문자열로 바꾼 후 [::-1]하여 역순, 그다음 int() 이용 정수로 바꾸기
- 0 미만인 -123이 주어지면 -1을 곱하며 123으로 바꾼 후 위와 같이 321로 바꾼 다음에 -1 곱하여 -321 바꾸기
- 마지막으로 그 결과가 범위를 벗어나면 0 반환
class Solution:
def reverse(self, x: int) -> int:
def positive(x):
return int(str(x)[::-1]) #수를 문자열로 바꾼 후 역순한 뒤 다시 정수로 바꾸는 함수
if x >= 0:
result = positive(x) #0이상이면 위 함수를 이용하여 역순
else:
result = -1*positive(-1*x) #0미만이면 양수 처리 후 위 함수 적용한 후 다시 음수 처리
if result < -2**31 or result >= 2**31: #범위 안에 있는지 체크
return 0
else:
return result
4. 다른 풀이
- 순서 뒤집을 때 문자열을 이용하지 않고 10을 나누는 것을 반복할 수 있음.
- 문자열을 이용하는 기존 풀이가 코드 가독성이 더 좋음.
- 하지만 정수가 매우 커지면 문자열로 바꾸는 과정이 느리기 때문에 효율은 이게 더 좋음.
class Solution:
def reverse(self, x: int) -> int:
MAX = 2**31 - 1
is_pos = x > 0
rev = 0
x = abs(x)
while x != 0:
if rev > MAX // 10:
return 0
rev = rev * 10 + x % 10
x //= 10
return rev if is_pos else -1*rev
- 나는 부호에 따라 if 문을 나누어 처리하였는데, 부호를 따로 변수에 저장해두면 코드 가독성이 좋다.
class Solution:
def reverse(self, x: int) -> int:
flag = -1 if x < 0 else 1
s = str(abs(x))
x = int(s[::-1])
return x*flag if x < 2**31 else 0
5. 배운 점
- 부호에 따라 경우를 나눌 때는 부호 변수를 이용하면 편하다.
- 가능하다면 type을 변환하지 않는 것이 효율적인 코드이다.
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 11(Container With Most Water, python) (1) | 2023.12.12 |
---|---|
LeetCode 8(String to Integer (atoi), python) (1) | 2023.12.11 |
LeetCode 6(Zigzag Conversio, Python) (0) | 2023.12.09 |
LeetCode 191(Number of 1 Bits, Python) (1) | 2023.12.08 |
LeetCode 190(Reverse Bits, Python) (1) | 2023.12.07 |