---
# System prepended metadata

title: 989. Add to Array-Form of Integer
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%);
    border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%);
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 989. Add to Array-Form of Integer


###### Link : https://leetcode.com/problems/add-to-array-form-of-integer/description/

## 題目
把兩個數字加起來，並以陣列方式回傳
## 程式碼 

```cpp=
class Solution {
public:
    vector<int> addToArrayForm(vector<int>& num, int k) {
        bool carryout = false;
        int i = num.size() - 1;//由陣列最後往前走
        while(k > 0 || carryout){//k仍大於0 或是需要進位
            if(i >= 0)
                num[i] += k % 10 + carryout;//目前k的個位數加上進位
            else//i < 0 代表需在陣列最左邊加上數字
                num.insert(num.begin(), k % 10 + carryout);
            carryout = false;//先將carryout設為false
            if(i >= 0 && num[i] > 9){//如i >= 0 且數字大於9
                num[i] -= 10;
                carryout = true;
            }
            else if(num[0] > 9){//i < 0(i == -1) 判斷最左邊位數是否需要進位
                num[0] -= 10;
                carryout = true;
            }
            k /= 10;
            if(i >= 0) --i;
        }
        return num;
    }
};
```