Two python solutions


  • 0

    I did this problem twice without realizing it, and I actually used two different methods. They are both relatively simple and straightforward.

        def plusOne(self, digits):
            """
            :type digits: List[int]
            :rtype: List[int]
            """
            cur = len(digits)-1
            while digits[cur] == 9:
                digits[cur] = 0
                cur -= 1
                # Now, check if cur is out of bounds. If so, pad a zero at front
                if cur < 0:
                    digits.insert(len(digits), 0)
                    cur = 0
            digits[cur] += 1
            return digits
    
        def plusOne_sol2(self, digits):
            """
            Another method I came up with when doing this problem the second time
            :type digits: List[int]
            :rtype: List[int]
            """
            carry = False
            digits[-1] += 1
            if digits[-1] > 9:
                digits[-1] = 0
                carry = True
            i = len(digits)-2
            while carry:
                if i < 0:
                    digits.insert(0, 1)
                    carry = False
                else:
                    digits[i] += 1
                    if digits[i] > 9:
                        digits[i] = 0
                        carry = True
                    else:
                        carry = False
                i -= 1
                        
            return digits
    

    BEST WISHES to interview prepers!


Log in to reply
 

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