Simple inline Python with explaination

  • 0
    class Solution(object):
        def plusOne(self, digits):
            :type digits: List[int]
            :rtype: List[int]
            digits = [0] + digits
            carry = 1
            index = len(digits)-1
            while carry:
                carry, digits[index] = divmod(digits[index]+1, 10)
                index -= 1
            if digits[0]:
                return digits
            return digits[1:]

    simply add 1 from the back. keep a carry so we can take the case if the current index has a value of 10, in which we will have to put a carry on the higher value. If carry ends so does the computation.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.