Code Logo

Add to Array-Form of Integer

Published at24 Jul 2026
Easy 0 views
Like0

The array form of an integer num is an array representing its digits in left-to-right order. For example, for num = 1321, the array form is [1,3,2,1]. Given the array form of an integer and an integer k, return the array form of their sum.

This is a carry state DP problem. Process the digits from right to left, maintaining a carry. Add the current digit plus k's digit (if any) plus any carry from the previous step. The new digit is the result modulo 10, and the carry is floor(result / 10).

The algorithm continues until all digits of the array are processed, k becomes 0, and carry is 0. The result is built in reverse and reversed at the end. This is O(max(n, log k)) time with O(max(n, log k)) space for the result.

Edge cases include empty array form (return digits of k), k = 0 (return original array), and the result having one more digit than the original (e.g., 999 + 1 = 1000).

The carry state DP processes digits from least significant to most significant, which is the reverse of how the array is stored. This is common in digit manipulation problems where the carry propagates from right to left. The while loop continues until all inputs and the carry are exhausted.

Example Input & Output

Example 1
Input
[], 123
Output
[1,2,3]
Explanation

Empty array + 123.

Example 2
Input
[1,2,0,0], 34
Output
[1,2,3,4]
Explanation

1200+34=1234.

Example 3
Input
[9,9,9], 1
Output
[1,0,0,0]
Explanation

999+1=1000.

Example 4
Input
[2,7,4], 181
Output
[4,5,5]
Explanation

274+181=455.

Example 5
Input
[1,2,3], 0
Output
[1,2,3]
Explanation

k=0.

Algorithm Flow

Recommendation Algorithm Flow for Add to Array-Form of Integer
Recommendation Algorithm Flow for Add to Array-Form of Integer

Solution Approach

Process right-to-left, tracking carry. Add digits from both inputs plus carry. Build result and reverse.

function solution(num, k) {
  var result = [];
  var carry = 0;
  var i = num.length - 1;
  while (i >= 0 || k > 0 || carry > 0) {
    var sum = carry;
    if (i >= 0) { sum += num[i]; i--; }
    if (k > 0) { sum += k % 10; k = Math.floor(k / 10); }
    result.push(sum % 10);
    carry = Math.floor(sum / 10);
  }
  return result.reverse();
}

Time O(max(n, log k)), Space O(max(n, log k)).

Best Answers

java
import java.util.*;
class Solution {
    public List<Integer> solution(int[] num, int k) {
        LinkedList<Integer> res=new LinkedList<>();
        int c=0,i=num.length-1;
        while (i>=0||k>0||c>0) {
            int s=c;
            if (i>=0) { s+=num[i]; i--; }
            if (k>0) { s+=k%10; k/=10; }
            res.addFirst(s%10);
            c=s/10;
        }
        return res;
    }
}