From 45bb95ff62086b0cb7fe4f388d44d4e66827498c Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 8 Sep 2022 15:40:52 +0800 Subject: [PATCH] vault backup: 2022-09-08 15:40:52 --- .obsidian/app.json | 4 +- OJ notes/pages/Leetcode Add-Two-Numbers.md | 58 +++++++++++++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/.obsidian/app.json b/.obsidian/app.json index ba8a803..491eadf 100644 --- a/.obsidian/app.json +++ b/.obsidian/app.json @@ -13,5 +13,7 @@ "defaultViewMode": "preview", "fileSortOrder": "byCreatedTime", "showFrontmatter": true, - "autoPairMarkdown": false + "autoPairMarkdown": false, + "strictLineBreaks": true, + "readableLineLength": true } \ No newline at end of file diff --git a/OJ notes/pages/Leetcode Add-Two-Numbers.md b/OJ notes/pages/Leetcode Add-Two-Numbers.md index 0c71370..d909c4f 100644 --- a/OJ notes/pages/Leetcode Add-Two-Numbers.md +++ b/OJ notes/pages/Leetcode Add-Two-Numbers.md @@ -74,6 +74,62 @@ You may assume the two numbers do not contain any leading zero, except the numbe Done by using elementary math. -Use only one +Use only one variable `tmp` to keep track of sum of 2 +digits and carries. ### Solution + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { + ListNode *appendNumber(ListNode *ptr, int num) { + ListNode *ans = new ListNode(num, nullptr); + ptr->next = ans; + + return ans; + } + +public: + ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { + ListNode *ptr1 = l1, *ptr2 = l2; + + // the minimum size is 1, so we can safely do this. + int tmp = ptr1->val + ptr2->val; + + ListNode *ans = new ListNode(tmp % 10); + + ListNode *tail = ans; + + tmp /= 10; + ptr1 = ptr1->next; + ptr2 = ptr2->next; + + while (ptr1 || ptr2 || tmp) { + if (ptr1) { + tmp += ptr1->val; + ptr1 = ptr1->next; + } + + if (ptr2) { + tmp += ptr2->val; + ptr2 = ptr2->next; + } + + tail = appendNumber(tail, tmp % 10); + + tmp /= 10; + } + + return ans; + } +}; +``` \ No newline at end of file