Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 2.02 KB

풀이_LC66.md

File metadata and controls

42 lines (30 loc) · 2.02 KB

🥴 LeetCode 66. Plus One

  • Date : 2021.07.18(일)
  • Time : 15분

Problem

  • Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself.

Constraints

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9

Example

  • Input: digits = [1,2,3]
  • Output: [1,2,4]
  • Explanation: The array represents the integer 123.



풀이

    def plusOne(self, digits: List[int]) -> List[int]:

        for i in range(len(digits)-1,-1,-1):
            digits[i] = digits[i] + 1
            if digits[i] < 10 :
                break
            else :
                digits[i] = 0
                if i == 0 :
                    digits.insert(0,1)

        return digits

: 숫자가 먼저 배열로 나눠져있다. 만약 102 라는 숫자가 있다면 102 -> [1,0,2] 로 되어있는것이다. 문제는 여기서 +1를 하는 문제이다! 생각해보니 다시 숫자로 바꿔서 +1을 해주고 배열로 바꾸는 방법도 있겠다.. 하지만 나는 배열 그대로 숫자를 더하는 방식을 구현했다. for문을 거꾸로 먼저 돌았다. 그리고 먼저 +1을 해주었다. 이때 만약 숫자가 10이 넘지 않는다면 그 다음자리에 영향을 끼치지 않는다는 말이므로 break문을 걸어서 for문을 끝냈다. 하지만 만약 10이 넘었다면 다음 자리에 영향을 줘야한다. 그래서 먼저 현재 자리수는 0으로 변경한 후 다음 자리수로 이동했다. 하지만 여기서도 예외가 발생할 수 있다. 현재 존재하는 자리수의 제일 앞까지 왔을 경우다. 예를 들면 999 -> 1000으로 넘어가야 하는 경우이다. 이때는 제일 앞자리수를 만들어줘야하기 때문에 insert를 이용해서 맨 앞자리에 1을 넣어주었다.