Re: [閒聊] 每日LeetCode
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;
}
};
---
怎麼連續兩天都是大數加法
補一下奇怪的 Python code:
class Solution(object):
def addToArrayForm(self, num, k):
"""
:type num: List[int]
:type k: int
:rtype: List[int]
"""
return [int(x) for x in str((int("".join(map(str, num))) + k))]
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.229.216 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1676420444.A.0BC.html
※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 08:31:48
推
02/15 08:32,
2年前
, 1F
02/15 08:32, 1F
※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 08:53:34
推
02/15 08:53,
2年前
, 2F
02/15 08:53, 2F
每天準時早八寫leetcode
※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 08:54:27
推
02/15 10:05,
2年前
, 3F
02/15 10:05, 3F
剛好最近的作息都在半夜起床而已
可能再過一陣子作息又改變了
推
02/15 10:41,
2年前
, 4F
02/15 10:41, 4F
推
02/15 12:50,
2年前
, 5F
02/15 12:50, 5F
推
02/15 12:50,
2年前
, 6F
02/15 12:50, 6F
※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 13:38:41
討論串 (同標題文章)
完整討論串 (本文為第 233 之 719 篇):