989. Add to Array-Form of Integer
给一个十进制的大数阵列 num 跟一个 integer k,
求两者相加后的结果。
Example 1:
Input: num = [1, 2, 0, 0], k = 34
Output: [1, 2, 3, 4]
Explanation: 1200 + 34 = 1234
Example 2:
Input: num = [2, 7, 4], k = 181
Output: [4, 5, 5]
Explanation: 274 + 181 = 455
Example 3:
Input: num = [2, 1, 5], k = 806
Output: [1, 0, 2, 1]
Explanation: 215 + 806 = 1021
解题思路:
跟昨天一样的大数加法,
不过变成了阵列跟整数做加法,
把阵列反转过来从末端对齐开始做直式加法,
注意长度问题不要存取超过边界就行了。
C++ code:
class Solution {
public:
vector<int> addToArrayForm(vector<int>& num, int k) {
reverse(num.begin(), num.end());
int length = max((int)num.size(), (int)ceil(log10(k + 1))) + 1;
num.resize(length);
for(int i = 0; i < num.size(); i++){
num[i] += k % 10;
k /= 10;
if(num[i] > 9){
num[i] -= 10;
num[i + 1] += 1;
}
}
if(num.back() == 0) num.pop_back();
reverse(num.begin(), num.end());
return num;
}
};