[leetcode-python3] 66. Plus One

shsh·2020년 12월 3일
0

leetcode

목록 보기
19/161

66. Plus One - python3

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.

My Answer 1: Accepted (Runtime: 32 ms / Memory Usage: 14.2 MB)

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        if digits[-1] != 9:
            digits[-1] += 1
            return digits
        
        i = -1
        flag = 0
        
        while digits[i] == 9:
            digits[i] = 0
            if i == len(digits) * -1:
                digits.insert(i, 1)
                flag = 1
            i -= 1
        
        if flag != 1:
            digits[i] += 1
        
        return digits

digits[-1] => 마지막 자리를 의미
맨 마지막에 1을 더하는 거니까
1) 마지막 자리가 9보다 작으면 1을 더하고 그대로 리턴
2) 마지막 자리가 9이면
마지막 자리부터 앞으로 나아가면서 1을 더함
이때 맨 앞자리(len(digits) * -1)까지 모두 9 면 맨 앞자리 앞에 1 을 insert. [ex. 9999 -> 10000]
flag 는 모든 자리가 9 임을 의미 => 아니라면 그냥 1을 더하고 리턴 [ex. 8999 -> 9000]

더 간단하게 풀 수도 있을 거 같지만 여기서 만족..

profile
Hello, World!

0개의 댓글

관련 채용 정보