581/670

581. Add to Array-Form of Integer

Easy

The array form of a non-negative integer writes its decimal digits as an array, most significant digit first: 1234 becomes [1, 2, 3, 4].

Your function receives num, the array form of some integer, and a non-negative integer k. Return the array form of num + k.

The catch: num can have up to 10⁴ digits, so the value it encodes is astronomically larger than any built-in fixed-width integer — you must add the way you did in grade school, digit by digit with a carry.

Example 1:

Input: num = [1, 2, 0, 0], k = 34

Output: [1, 2, 3, 4]

Explanation: num encodes 1200, and 1200 + 34 = 1234, whose array form is [1, 2, 3, 4].

Example 2:

Input: num = [2, 7, 4], k = 181

Output: [4, 5, 5]

Explanation: 274 + 181 = 455.

Constraints:

  • 1 ≤ num.length ≤ 10⁴
  • 0 ≤ num[i] ≤ 9
  • num has no leading zeros, except num = [0] itself
  • 0 ≤ k ≤ 10⁴

Hints:

Work from the last digit of num (the ones place) toward the front, exactly like column addition on paper. What value do you carry into each column?

You don't need to split k into digits first: add all of k to the last column, keep sum % 10 as the digit, and pass sum / 10 — which still contains the rest of k — as the carry into the next column.

When you run out of digits in num, the leftover carry may still be several digits long (think [9] + 9999). Peel it off with % 10 and / 10 until it hits zero.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: num = [1, 2, 0, 0], k = 34

Expected output: [1, 2, 3, 4]