Add to Array-Form of Integer - Problem

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 num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

Input & Output

Example 1 — Basic Addition
$ Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
💡 Note: Array [1,2,0,0] represents 1200. Adding 34 gives us 1234, which is [1,2,3,4] in array form.
Example 2 — Small Array
$ Input: num = [2,7,4], k = 181
Output: [4,5,5]
💡 Note: Array [2,7,4] represents 274. Adding 181 gives us 455, which is [4,5,5] in array form.
Example 3 — Carry Overflow
$ Input: num = [9,9,9], k = 1
Output: [1,0,0,0]
💡 Note: Array [9,9,9] represents 999. Adding 1 gives us 1000, which requires expanding to [1,0,0,0].

Constraints

  • 1 ≤ num.length ≤ 104
  • 0 ≤ num[i] ≤ 9
  • num does not contain any leading zeros except for the zero itself
  • 1 ≤ k ≤ 104

Visualization

Tap to expand
Add to Array-Form of Integer INPUT num = [1, 2, 0, 0] 1 2 0 0 i=0 i=1 i=2 i=3 k = 34 3 4 Represents: 1200 + 34 = ? Array [1,2,0,0] Integer k = 34 ALGORITHM STEPS 1 Start from Right Process digits right to left 2 Add digit + k%10 sum = num[i] + (k % 10) 3 Handle Carry k = k/10 + sum/10 4 Store Result result[i] = sum % 10 Computation Steps: i=3: 0+4=4, k=3 --> 4 i=2: 0+3=3, k=0 --> 3 i=1: 2+0=2, k=0 --> 2 i=0: 1+0=1, k=0 --> 1 Result: [1,2,3,4] FINAL RESULT Output: [1, 2, 3, 4] 1 2 3 4 Verification: 1200 + 34 = 1234 OK Array form of 1234 is [1, 2, 3, 4] return [1, 2, 3, 4] Key Insight: Treat k as a number and add it digit by digit from the rightmost position. Use k % 10 to get the current digit of k, and k / 10 to move to the next digit. Carry is naturally handled by adding overflow to k for the next iteration. TutorialsPoint - Add to Array-Form of Integer | Digit-by-Digit Addition with Carry
Asked in
Google 15 Apple 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen