NeetCode #860LC-989EasyBit Manipulation
← Back to All Problems

#860 · #989 · Add to Array-Form of Integer(数组形式的整数加法)

📌 Problem Statement & Constraints

The array num represents the digits of a non-negative integer in big-endian order. Given num and an integer k, return the array-form of num + k. Constraints: 1 <= num.length <= 10^4, 0 <= num[i] <= 9, 0 <= k <= 10^4.

💡 Core Algorithmic Approaches

  1. Add k to the number digit by digit from the least significant end, using k itself as the running carry.
  2. At each position, add the current digit to the carry, emit carry % 10, and keep carry // 10.
  3. The loop continues while digits remain or the carry is non-zero, so extra digits produced by k are appended.
  4. Reverse the collected digits to restore big-endian order.

💻 Benchmark Python3 Implementation

class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        i = len(num) - 1
        carry = k
        res = []
        while i >= 0 or carry:
            if i >= 0:
                carry += num[i]           # fold the digit into the carry
                i -= 1
            res.append(carry % 10)        # digit to keep
            carry //= 10                  # carry into the next position
        return res[::-1]

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(max(len(num), log k)): one step per digit of the result.
💾 Space Complexity
O(1) beyond the output.

⚠️ Interview Pitfalls & Follow-ups

  • Converting num to an integer: Python can do it, but the problem is designed to exercise big-number addition by hand.
  • Stopping when the digits run out: a large k can add extra leading digits, so the loop must also continue while carry is non-zero.
  • Forgetting to reverse: digits are produced least-significant first.
  • Handling k == 0 separately: unnecessary, since the loop still emits every existing digit.