Python generalization to plus n (0<= n <=9)


  • 0
    P
    def plus_n(digits, n):
        N = len(digits)
        if digits[-1] + n < 10:
            digits[-1] += n
            return digits
        else:
            digits[-1] = (digits[-1] + n) % 10
            for i in xrange(N-2, -1, -1):
                if digits[i] == 9:
                    digits[i] = 0
                else:
                    digits[i] += 1
                    return digits
    
        # all 9s except for the last digit
        new = [0] * (N + 1)
        new[0] = 1
        return new

Log in to reply
 

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