Notice
Recent Posts
Recent Comments
Link
오늘도 개발
17. Plus One 본문
문제
큰 정수를 표현하는 digits 배열을 인자로 받은 후
해당 정수에 1을 더한 결과를 배열로 반환하라.
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
내가 생각한 해결 방식 1)
마지막 요소에 1 더하고, 마지막 요소부터 iteration 시작.
현재 요소가 10이 아니면 배열을 바로 반환한다.
현재 요소가 10이면 현재 요소를 0으로 바꾼다.
현재 요소가 0번째 인덱스가 아니면 앞 요소에 1을 더한다.
현재 요소가 0번째 인덱스이면 앞 인덱스에 1을 삽입한다.
def plusOne(digits):
digits[-1] += 1
for i in range(len(digits) - 1, -1, -1):
if digits[i] == 10:
digits[i] = 0
if i != 0:
digits[i - 1] += 1
else:
digits.insert(0, 1)
return digits
else:
return digits
내가 생각한 해결 방식 2)
배열을 숫자로 변환한 후 1을 더하고, 다시 배열로 변환해서 반환한다.
def plusOne(digits):
number = int(''.join(str(digit) for digit in digits))
return list(str(number + 1))
다른 사람의 해결 방식
def plusOne(digits):
for i in reversed(range(len(digits))):
# 현재 요소가 9가 아니면 1 더하고 iteration 끝
if digits[i] != 9:
digits[i] += 1
break
# 현재 요소가 9이면 0으로 바꿈
else:
digits[i] = 0
# 첫번째 요소가 0이면 앞 인덱스에 1 삽입
if digits[0] == 0:
digits.insert(0, 1)
return digits
'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글
| 20. Pascal's Triangle (1) | 2022.09.23 |
|---|---|
| 19. Spiral Matrix (1) | 2022.09.22 |
| 16. Largest Number At Least Twice of Others (0) | 2022.09.14 |
| 15. Find Pivot Index(1991) (0) | 2022.09.13 |
| 14. Find All Numbers Disappeared in an Array (0) | 2022.06.05 |