LeetCode 989: Add to Array-Form of Integer Solution
Master LeetCode problem 989 (Add to Array-Form of Integer), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can simulate the addition process of adding the number k to the array-form of the integer num from right to left. We start by adding k to the last digit of num, then propagate any carry to the next digit until there are no more digits in num or no more carry.
Algorithm:
- Initialize a variable
carryto 0 to store the carry during addition. - Iterate through the digits of
numfrom right to left. - Add the current digit of
numwith the corresponding digit ofkand the carry. - Update the current digit of
numto be the sum of the three values mentioned above. - Update the carry to be the floor division of the sum by 10.
- If there are no more digits in
k, break out of the loop. - If there are no more digits in
numbut there is still a carry, continue adding the carry to the remaining digits ofk. - Reverse the updated
numarray to get the correct array-form of the sum.
Time Complexity:
The time complexity of this algorithm is O(max(N, log(K))), where N is the number of digits in the array num and K is the value of k.
Space Complexity:
The space complexity of this algorithm is O(max(N, log(K))) to store the result array.
:
Solution Code
import java.util.LinkedList;
import java.util.List;
class Solution {
public List<Integer> addToArrayForm(int[] num, int k) {
LinkedList<Integer> result = new LinkedList<>();
int i = num.length - 1;
int carry = 0;
while (i >= 0 || k > 0 || carry > 0) {
int sum = carry;
if (i >= 0) {
sum += num[i];
i--;
}
if (k > 0) {
sum += k % 10;
k /= 10;
}
result.addFirst(sum % 10);
carry = sum / 10;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 989 (Add to Array-Form of Integer)?
This page provides optimized solutions for LeetCode problem 989 (Add to Array-Form of Integer) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 989 (Add to Array-Form of Integer)?
The time complexity for LeetCode 989 (Add to Array-Form of Integer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 989 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 989 in Java, C++, or Python.