알고리즘 스터디

[Leetcode/파이썬] 66. Plus One

난쟁이 개발자 2025. 5. 11. 16:53
반응형

Plus One

Difficulty: Easy


You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

 

Example 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].

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].

Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

 

Constraints:

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • digits does not contain any leading 0's.

 

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        for i in range(len(digits)-1, -1, -1) :
            nxt = digits[i] + 1 # 다음 : 현재에서 + 1
            if nxt != 10 :      # 가장 마지막 자리 숫자에 + 1 을 한 결과가 10이 아니라면
                digits[i] = nxt # 다음 순서로 갱신 후 반환
                return digits
            # 만약 nxt 가 10 이라면
            digits[i] = 0   # 해당 순서를 0으로 만들고 i + 1 을 for문에서 진행시킴
            if i == 0 :     # i가 첫 번째 자리 수를 가리키면
                return [1] + digits # 올림 처리를 한 후 반환

처음에 이 코드를 이해하는 데 며칠 걸렸다. 올림 처리를 어떤 방식으로 할까에 대해서 고민이 많았던 문제였다. for문을 반대로 돌면서 가장 아래에서 부터 + 1 씩 진행하면서 10이 아니라면 바로 반환하는 방식을 채택하고 있는 코드이다. 

만약 10이라면 0으로 바꾼 후 for문을 자연스럽게 진행시키면서 다음 자리 수에서 + 1 을 진행하면 전체적으로는 9를 10으로, 90을 100으로 만드는 방식이기 때문에 신선했다. 

가장 마지막으로는 i == 0 은, 가장 앞자리가 9 에서 10으로 바뀌는 순간에서는 0으로 바꾼 후 리스트 가장 앞에 [1]을 더하는 방식이다. 

반응형