Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Docker
- programmers
- leetcode
- 더현대서울 맛집
- 파이썬
- ubuntu
- dacon
- Real or Not? NLP with Disaster Tweets
- 자연어처리
- 백준
- Git
- 우분투
- 프로그래머스
- hackerrank
- SW Expert Academy
- 캐치카페
- PYTHON
- 맥북
- gs25
- github
- Baekjoon
- Kaggle
- 데이콘
- 프로그래머스 파이썬
- 코로나19
- 편스토랑 우승상품
- ChatGPT
- AI 경진대회
- 금융문자분석경진대회
- 편스토랑
Archives
- Today
- Total
솜씨좋은장씨
[leetCode] 397. Integer Replacement (Python) 본문
728x90
반응형
Given a positive integer n, you can apply one of the following operations:
- If n is even, replace n with n / 2.
- If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: n = 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
Example 3:
Input: n = 4
Output: 2
Constraints:
- 1 <= n <= 231 - 1
첫 번째 시도 ( 시간 초과 )
class Solution:
def integerReplacement(self, n: int) -> int:
cnt = 0
cnt2 = 0
n2 = n
while True:
if n == 1:
break
else:
if n % 2 == 1:
n = n -1
cnt = cnt + 1
elif n % 2 == 0:
n = n // 2
cnt = cnt + 1
while True:
if n2 == 1:
break
else:
if n % 2 == 1:
n2 = n2 + 1
cnt2 = cnt2 + 1
elif n % 2 == 0:
n2 = n2 // 2
cnt2 = cnt2 + 1
return min([cnt, cnt2])
첫번째 시도는 먼저 홀수일 경우 - 1 을 하면서 짝수일 경우 2로 나눈 방법과
홀수일 경우 +1을 하면서 짝수일 경우 2로 나눈 방법 2가지 방법 중 더 적은 횟수를 정답으로 설정했습니다.
Solution
class Solution:
def integerReplacement(self, n: int) -> int:
cnt = 0
while True:
if n == 1:
break
elif n == 3:
return cnt + 2
else:
if n % 2 == 1:
if ((n-1) // 2) % 2 == 1:
n = n + 1
else:
n = n -1
cnt = cnt + 1
elif n % 2 == 0:
n = n // 2
cnt = cnt + 1
return cnt
이번에는 -1 방식 +1 방식을 모두 해보는 것이 아니라
-1로 뺐을때의 숫자가 2로 나누었을때 홀수일 경우 +1을 하고 그렇지 않을 경우 -1을 하도록 했습니다.
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[leetCode] 47. Permutations II (Python) (0) | 2020.11.17 |
---|---|
[leetCode] 19. Remove Nth Node From End of List (Python) (0) | 2020.11.16 |
[leetCode] 747. Largest Number At Least Twice of Others (Python) (0) | 2020.11.13 |
[leetCode] 859. Buddy Strings (Python) (0) | 2020.11.12 |
[leetCode] 1394. Find Lucky Integer in an Array (Python) (0) | 2020.11.11 |
Comments