989. Add to Array-Form of Integer

as 66, 415 solution style

T: O(min(n, m)

S: O(min(n, m)

class Solution {
    public List<Integer> addToArrayForm(int[] num, int k) {
        List<Integer> res = new ArrayList<>();
        String kstr = String.valueOf(k);
        int numIdx = num.length - 1;
        int kIdx = kstr.length() - 1;
        
        int carry = 0;
        while (numIdx >= 0 || kIdx >= 0) {
            int num1 = numIdx >= 0 ? num[numIdx] : 0;
            int num2 = kIdx >= 0 ? kstr.charAt(kIdx) - '0' : 0;
            int sum = num1 + num2 + carry;
            carry = sum/10;
            res.add(sum%10);
            
            numIdx--;
            kIdx--;
        }
        if (carry == 1) {
            res.add(1);
        }
        List<Integer> result = new ArrayList<>();
        for (int i = res.size() - 1; i >= 0; i--) {
            result.add(res.get(i));
        }
        return result;
    }
}j

if we add data with res.add(0, xx), at last, we don't need reverse list, but add in 0 index will make array shift, so it's slower.

solution 2, k as carry

this's really clean, but be careful of while loop for k

class Solution {
    public List<Integer> addToArrayForm(int[] num, int k) {
        List<Integer> res = new ArrayList<>();
        
        for (int i = num.length - 1; i >= 0; i--) {
            res.add(0, (num[i] + k)%10);
            k = (num[i] + k)/10;
        }
        while (k > 0) {
            res.add(0, k%10);
            k = k/10;
        }
        return res;
    }
}j

Last updated