精華區beta Marginalman 關於我們 聯絡資訊
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
Rushia: 大師02/15 08:32
※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 08:53:34
NTHUlagka: 太早了吧 大師02/15 08:53
每天準時早八寫leetcode ※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 08:54:27
NTHUlagka: 早八太扯了吧 學生時代以後就沒那麼早了02/15 10:05
剛好最近的作息都在半夜起床而已 可能再過一陣子作息又改變了
pandix: 大師02/15 10:41
greenertea: 大師02/15 12:50
a9486l: 大師02/15 12:50
※ 編輯: idiont (140.113.229.216 臺灣), 02/15/2023 13:38:41