Advertisement
1988coder

989. Add to Array-Form of Integer

Feb 10th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/add-to-array-form-of-integer/
  3. import java.util.LinkedList;
  4. import java.util.List;
  5.  
  6. /**
  7.  * Iterate over the input array from end to start and keep adding K.
  8.  *
  9.  * Time Complexity: O(N + K)
  10.  *
  11.  * Space Complexity: O(1)
  12.  *
  13.  * N = Length of A. K = Number of digits in K
  14.  */
  15. class Solution {
  16.     public List<Integer> addToArrayForm(int[] A, int K) {
  17.         LinkedList<Integer> result = new LinkedList<>();
  18.         if (A == null) {
  19.             throw new IllegalArgumentException("Input array A is null");
  20.         }
  21.  
  22.         for (int i = A.length - 1; i >= 0; i--) {
  23.             int sum = A[i] + K;
  24.             result.addFirst(sum % 10);
  25.             K = sum / 10;
  26.         }
  27.  
  28.         while (K > 0) {
  29.             result.addFirst(K % 10);
  30.             K /= 10;
  31.         }
  32.  
  33.         return result;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement