# Leetcode 989. Add to Array-Form of Integer ###### tags: `leetcode` `daily` [題目連結](https://leetcode.com/problems/add-to-array-form-of-integer/description/) # Method :::info :bulb: **作法講解**: concept, get value in num from index n-1 to 0, get value in k from bit 32 to bit 0, for each round, get value a from num[i] if i >= 0. get value b from k % 10 put (a + b + overflow) % 10 into vector output. set overflow to (a + b + overflow) / 10 網路上的解釋方式: initialize "carry" to 0, "i" to the index of last digit of num loop while there is a digit left in k, or there are digits left in num or there is a carry value compute the sum by adding the carry, the last digit of k(if k has digit left), the i-th digit of num(if num has digits left compute the carry by taking the sum divided by 10 Add the digit to the back of the "ans" vector by taking the sum mod 10 Decrement i, and divide k by 10 reverse "ans" vector, and return it https://leetcode.com/problems/add-to-array-form-of-integer/solutions/3186990/day-46-c-easiest-beginner-friendly-sol-o-max-n-log-k-time-and-o-max-n-log-k-space/?orderBy=hot ::: TC: O(N) SC: O(N) :::spoiler 完整程式碼 ```cpp= class Solution { public: vector<int> addToArrayForm(vector<int>& num, int k) { int n = num.size(); int idx = n - 1; int overflow = 0; vector<int> output; while((idx >= 0) || k) { int a = (idx >= 0) ? num[idx] : 0; int b = k % 10; int v = a + b + overflow; output.push_back(v % 10); overflow = v / 10; idx--; k = k/10; } if(overflow) { output.push_back(overflow); } reverse(output.begin(), output.end()); return output; } }; ``` :::