Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/add-to-array-form-of-integer/
- import java.util.LinkedList;
- import java.util.List;
- /**
- * Iterate over the input array from end to start and keep adding K.
- *
- * Time Complexity: O(N + K)
- *
- * Space Complexity: O(1)
- *
- * N = Length of A. K = Number of digits in K
- */
- class Solution {
- public List<Integer> addToArrayForm(int[] A, int K) {
- LinkedList<Integer> result = new LinkedList<>();
- if (A == null) {
- throw new IllegalArgumentException("Input array A is null");
- }
- for (int i = A.length - 1; i >= 0; i--) {
- int sum = A[i] + K;
- result.addFirst(sum % 10);
- K = sum / 10;
- }
- while (K > 0) {
- result.addFirst(K % 10);
- K /= 10;
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement