|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * 989. Add to Array-Form of Integer |
| 9 | + * |
| 10 | + * For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1]. |
| 11 | + * |
| 12 | + * Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * |
| 16 | + * Input: A = [1,2,0,0], K = 34 |
| 17 | + * Output: [1,2,3,4] |
| 18 | + * Explanation: 1200 + 34 = 1234 |
| 19 | + * Example 2: |
| 20 | + * |
| 21 | + * Input: A = [2,7,4], K = 181 |
| 22 | + * Output: [4,5,5] |
| 23 | + * Explanation: 274 + 181 = 455 |
| 24 | + * Example 3: |
| 25 | + * |
| 26 | + * Input: A = [2,1,5], K = 806 |
| 27 | + * Output: [1,0,2,1] |
| 28 | + * Explanation: 215 + 806 = 1021 |
| 29 | + * Example 4: |
| 30 | + * |
| 31 | + * Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1 |
| 32 | + * Output: [1,0,0,0,0,0,0,0,0,0,0] |
| 33 | + * Explanation: 9999999999 + 1 = 10000000000 |
| 34 | + * |
| 35 | + * Note: |
| 36 | + * |
| 37 | + * 1 <= A.length <= 10000 |
| 38 | + * 0 <= A[i] <= 9 |
| 39 | + * 0 <= K <= 10000 |
| 40 | + * If A.length > 1, then A[0] != 0 |
| 41 | + */ |
| 42 | +public class _989 { |
| 43 | + public static class Solution1 { |
| 44 | + public List<Integer> addToArrayForm(int[] A, int K) { |
| 45 | + List<Integer> kDigitsReversed = new ArrayList<>(); |
| 46 | + int divisor = 10; |
| 47 | + while (K != 0) { |
| 48 | + kDigitsReversed.add(K % divisor); |
| 49 | + K /= 10; |
| 50 | + } |
| 51 | + List<Integer> result = new ArrayList<>(); |
| 52 | + int prevFlow = 0; |
| 53 | + for (int i = A.length - 1, j = 0; i >= 0 || j < kDigitsReversed.size(); i --, j++) { |
| 54 | + int sum; |
| 55 | + if (i >= 0 && j < kDigitsReversed.size()) { |
| 56 | + sum = A[i] + kDigitsReversed.get(j); |
| 57 | + } else if (i >= 0) { |
| 58 | + sum = A[i]; |
| 59 | + } else { |
| 60 | + sum = kDigitsReversed.get(j); |
| 61 | + } |
| 62 | + int flow = 0; |
| 63 | + if (prevFlow != 0) { |
| 64 | + sum += prevFlow; |
| 65 | + } |
| 66 | + if (sum > 9) { |
| 67 | + flow = 1; |
| 68 | + } |
| 69 | + sum %= 10; |
| 70 | + prevFlow = flow; |
| 71 | + result.add(sum); |
| 72 | + } |
| 73 | + if (prevFlow != 0) { |
| 74 | + result.add(prevFlow); |
| 75 | + } |
| 76 | + Collections.reverse(result); |
| 77 | + return result; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments