Plus One

Problem Id: 66 Difficulty: Easy Tag: Array


Intuition

This is a math problem. When add 1 to an integer, we first add 1 to the last number of the integer, then if it is greater or equal to 10, we minus it by 10 and add 1 to the previous value of that value.

Solution


class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        i = len(digits) - 1
        add = 1
        while i >= 0:
            digits[i] += add
            if digits[i] < 10:
                add = 0
                break
            else:
                digits[i] -= 10
                i -= 1
                add = 1
        if add:
            return [1] + digits
        else:
            return digits