#66 Plus One Python solution


  • 0
    G

    Traverse from the end of the list and add 1 to the end element and carry the carry forward to the previous elements. Once all elements are iterated check whether carry forward is greater than 0 or not and insert at the start the list accordingly.
    Time Complexity: O(N)
    Space Complexity: O(1)

    class Solution(object):
        def plusOne(self, digits):
            """
            :type digits: List[int]
            :rtype: List[int]
            """
            carry = 1
            for i in range(len(digits)-1,-1,-1):
                temp = digits[i]+carry
                digits[i]=temp%10
                carry = temp/10
            if carry>0:
                digits.insert(0,carry)
            return digits
                
    

Log in to reply
 

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