作者:
idiont (supertroller)
2023-02-15 08:20:42989. 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;
}
};