Add to Array-Form of Integer
Problem
num is the array-form of a non-negative integer (most-significant digit first). Return the array-form of num + k.
num = [1,2,0,0], k = 34[1,2,3,4]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;
}
Explanation
This is just grade-school addition, done one column at a time from right to left, with a twist: instead of a tiny carry, we let the whole integer k ride along as the carry.
We walk the digit array from the last index i backwards. At each step we fold the current digit into k with k += num[i]. Then the last digit of k (that is k % 10) becomes the next output digit, and we drop that digit off with k //= 10, leaving the rest to carry forward.
The loop keeps going while either there are digits left (i >= 0) or there is still some k to spend (k > 0). This neatly handles the case where the sum is longer than the original number.
Since we build the answer least-significant digit first, we reverse out at the end to put the most significant digit first.
Example: num = [1,2,0,0], k = 34. Rightmost 0+34=34 → push 4, carry 3; next 0+3=3 → push 3, carry 0; then 2, then 1. Reversed gives [1,2,3,4].