2019년 5월 25일 토요일

[leetcode] 66. Plus One

원문)
Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.

번역)
양수의 값이 있는 배열이 주어졌을때 +1을 하라.
최상위 숫자가 리스트의 첫째자리에 있고 각 요소들은 한자리씩 들어가 있다.
숫자 0을 제외하고 나머지 최상위 자리에는 0이 들어갈 수 없다고 가정하라.


예제)


Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.


문제접근)
각 요소는 한자리 숫자만 들어갈 수 있다.
만약 10이면 1, 0 이렇게 2자리로 들어가야 한다.
우선 최하위 부터 자릿수 이동이 일어나야 하므로 기존 리스트를 뒤집어주고
10이 넘어가면 carry를 올려줘서
최종적으로 carry가 있을경우는 자릿수를 하나 더 올려준다.

코드)


class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        digits = digits[::-1]
        digits[0] += 1
        carry = 0

        for i in range(len(digits)):
            if carry:
                digits[i] += 1
                carry = 0
                
            carry = digits[i] // 10
            digits[i] = digits[i] % 10
        
        if carry:
            digits.append(1)
        return digits[::-1]

댓글 없음:

댓글 쓰기