Re: [閒聊] 每日LeetCode

看板Marginalman作者 (supertroller)時間2年前 (2023/02/15 08:20), 2年前編輯推噓6(600)
留言6則, 5人參與, 2年前最新討論串233/719 (看更多)
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
文章代碼(AID): #1Zx2LS2y (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1Zx2LS2y (Marginalman)