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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Addition digit by digit
Here is the approach:
- Start from the least significant digit of
num
(the last element of the array) and add digits ofk
to it. - Manage the carry during addition.
- If there are remaining digits in
k
after processing all digits ofnum
, continue adding the carry to those digits. - If there’s any remaining carry after processing both
num
andk
, add those carry digits to the result. - The final result should be reversed to get the correct order of the array-form.\
Here are the steps:
- Initialize variables to hold the carry and the result array.
- Traverse
num
andk
from right to left, add corresponding digits, and manage the carry. - If digits in
k
are exhausted beforenum
, continue processing the remaining digits ofnum
with the carry. - If digits in
num
are exhausted beforek
, convert and process remaining digits ofk
. - Add remaining carry if any.
Code
|
|
|
|
Complexity
- Time:
O(n + m)
, wheren
is the length ofnum
andm
is the number of digits ink
. - Space:
O(max(n, m))
, The space required to store the result array.