Increment an Arbitrary-Precise Integer

Write a program which takes as input an array of digits encoding a non-negative decimal integer D and updates the array to represent the integer D + 1. For example, if the input is (1,2,9) then you should update the array to (1,3,0). Your algorithm should work even if it is implemented in language that has finite-precision arithmetic.

Solution: The brute force method would be to covert the array input into integer, increment the integer then convert it back. But this approach will fail on inputs that encode integers outside the range of integer values.

A cleaner approach to this would be to add directly to the array itself. The algorithm written bellow mimics the algorithm taught in grade-school for adding integers, which entails adding to the least significant digit, and propagate carries.

def plus-one (A) :
    A[-1] += 1
    for i  in reversed(range(1, len(A))):
        if A[i] != 0:
            break
        A[i] = 0
        A[i -1] += 1
     if A[0] == 10:
    # There is a carry-out, so we need one more  
    # digit to store the result. A slick way to do this is to 
    # append a 0 at the end of the array, and update the first 
    # entry to 1.
    A[0] = 1
    A.append(0)
return A

A variant to this question: Given two binary strings, return their sum (also a binary string).

Leave a comment