5 Best Ways to Add One to a Number Represented as a Digit List in Python

πŸ’‘ Problem Formulation: Given a digit list representing a non-negative integer, we want to add one to the integer and return the resulting number as a digit list. For example, if the input is [1, 2, 3], which represents the number 123, after adding one, the output should be [1, 2, 4].

Method 1: Iterative Approach

Using an iterative approach, we manually simulate the addition process from right to left, carrying the remainder as we would on paper. This method loops through the list in reverse and handles carrying over for each digit.

Here’s an example:

def add_one(digits):
    carry = 1
    for i in range(len(digits) - 1, -1, -1):
        if carry:
            if digits[i] < 9:
                digits[i] += 1
                carry = 0
            else:
                digits[i] = 0
    if carry:
        digits.insert(0, 1)
    return digits

print(add_one([1, 2, 3]))

Output: [1, 2, 4]

The function add_one() takes a list of digits, adds one to the last element, and handles carrying over. If there’s still a carry after the loop, it inserts a 1 at the beginning of the list. This method works well for small numbers.

Method 2: Convert to Integer and back

We can convert the entire list to an integer, add one, then convert it back to a list. This is the most straightforward approach, using Python’s type conversion capabilities.

Here’s an example:

def add_one(digits):
    num = int(''.join(map(str, digits))) + 1
    return [int(i) for i in str(num)]

print(add_one([9, 9, 9]))

Output: [1, 0, 0, 0]

This snippet converts the list of digits into a string, then to an integer, adds one, and splits the resulting number back into a list of digits. It’s very concise but not optimal for very large numbers due to type conversion overhead.

Method 3: Using Python’s BigInteger Support

Python naturally handles big integers, making the type conversion method very efficient for large numbers. In this method, we essentially do the same thing as Method 2, but it is worth mentioning separately because Python’s integer is not limited by size.

Here’s an example:

def add_one(digits):
    # This function is practically the same as the Method 2
    # Reiterating its implementation to emphasize Python's big integer capability
    num = int(''.join(map(str, digits))) + 1
    return [int(i) for i in str(num)]

print(add_one([1, 8, 9, 9, 9, 9, 9, 9, 9]))

Output: [1, 9, 0, 0, 0, 0, 0, 0, 0]

Despite being similar to Method 2, it’s worth highlighting Python’s handling of large integers. It shows how this approach remains effective regardless of the number’s size with no particular constraints on integer values.

Method 4: Recursion

This method incorporates a recursive function to end the addition process once there is no carry or we reach the beginning of the list. It’s a more academic approach but illustrates an alternative using recursion.

Here’s an example:

def add_one(digits, index):
    if index < 0:
        digits.insert(0, 1)
        return digits
    if digits[index] < 9:
        digits[index] += 1
        return digits
    digits[index] = 0
    return add_one(digits, index-1)

print(add_one([2, 9, 9], len([2, 9, 9])-1))

Output: [3, 0, 0]

The recursive function add_one() calls itself by reducing the index. If it encounters a 9, it sets the digit to 0 and carries the 1 to the next call. If it’s the beginning of the list, it inserts a 1. It is elegant but not the most efficient for large lists due to recursion depth limitations.

Bonus One-Liner Method 5: List Comprehension with Integer Conversion

This method uses list comprehension with the integer conversion combo in a one-liner. It showcases Python’s ability to perform complex operations in concise expressions.

Here’s an example:

print([(int(i) for i in str(int(''.join(map(str, [1, 2, 3]))) + 1))])

Output: [1, 2, 4]

The one-liner uses list comprehension to execute the conversion to an integer, adds one, then iterates through the string representation of the result to convert back to a list of integers. It’s concise but less readable and therefore unsuitable for complex logic or very large numbers.

Summary/Discussion

  • Method 1: Iterative Approach. Handles digit overflow correctly. Easy to understand and follows the manual addition process. Can be slow for very large lists and numbers.
  • Method 2: Convert to Integer and back. Simple and straightforward. Utilizes built-in Python features for type conversion. Not as efficient for huge numbers due to overhead in conversion.
  • Method 3: Using Python’s BigInteger Support. Capitalizes on Python’s strength in handling big integers with the same simplicity as Method 2. No specific weaknesses, just a highlight of Python’s bigint handling.
  • Method 4: Recursion. Academic interest and clean approach to illustrate a recursive solution. Not suitable for large lists due to python recursion call stack limit.
  • Bonus Method 5: List Comprehension with Integer Conversion. Extremely concise. Demonstrates the elegance of Python’s one-liners but at the expense of reduced readability and understanding.