The problem is taken from LeetCode: “Add to Array-Form of Integer”.
Given an array num
representing a non-negative integer num
, and an integer k
, return the array-form of the integer num + k
. The array-form of an integer is an array representing its digits in left to right order.
num = [1,2,0,0]
, k = 34
[1,2,3,4]
num = [2,7,4]
, k = 181
[4,5,5]
num = [2,1,5]
, k = 806
[1,0,2,1]
num
be empty?
num
will represent a non-negative integer, so it must contain at least one digit.k
be negative?
k
is guaranteed to be a non-negative integer.k
to the integer value.def addToArrayForm(num, k):
# Step 1: Convert array-form to an integer
num_as_int = 0
for digit in num:
num_as_int = num_as_int * 10 + digit
# Step 2: Add k to the integer value
num_as_int += k
# Step 3: Convert the result back to array-form
result = [int(d) for d in str(num_as_int)]
return result
O(n)
where n
is the length of the array.k
is a constant time operation: O(1)
.O(m)
where m
is the number of digits in the result (num_as_int + k
).O(n + m)
.In most cases, m
(number of digits in the resultant sum) will be close to n
, so the time complexity can be approximated to O(n)
.
num
: Verify the function performs correctly when num
has only one digit.k
causes digits to reflect a carry over, e.g., num = [9, 9, 9]
and k = 2
.k
: Function must handle cases where k
has more digits than num
.The above code provides a comprehensive solution to the problem by accurately converting the input format and performing the requested operation while considering time efficiency.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?