Add to Array-Form of Integer

easy array math

Problem

num is the array-form of a non-negative integer (most-significant digit first). Return the array-form of num + k.

Inputnum = [1,2,0,0], k = 34
Output[1,2,3,4]
Walk right-to-left; carry = (digit + carry) / 10; while carry remains, continue.

def addToArrayForm(num, k):
    i = len(num) - 1
    out = []
    while i >= 0 or k > 0:
        if i >= 0: k += num[i]; i -= 1
        out.append(k % 10)
        k //= 10
    return out[::-1]
function addToArrayForm(num, k) {
  let i = num.length - 1;
  const out = [];
  while (i >= 0 || k > 0) {
    if (i >= 0) { k += num[i]; i--; }
    out.push(k % 10);
    k = Math.floor(k / 10);
  }
  return out.reverse();
}
class Solution {
    public List<Integer> addToArrayForm(int[] num, int k) {
        LinkedList<Integer> out = new LinkedList<>();
        int i = num.length - 1;
        while (i >= 0 || k > 0) {
            if (i >= 0) { k += num[i]; i--; }
            out.addFirst(k % 10);
            k /= 10;
        }
        return out;
    }
}
vector<int> addToArrayForm(vector<int>& num, int k) {
    vector<int> out;
    int i = (int)num.size() - 1;
    while (i >= 0 || k > 0) {
        if (i >= 0) { k += num[i]; i--; }
        out.push_back(k % 10);
        k /= 10;
    }
    reverse(out.begin(), out.end());
    return out;
}
Time: O(max(n, log k)) Space: O(max(n, log k))