vault backup: 2022-09-08 15:40:52
This commit is contained in:
parent
484bcdf915
commit
45bb95ff62
4
.obsidian/app.json
vendored
4
.obsidian/app.json
vendored
|
@ -13,5 +13,7 @@
|
|||
"defaultViewMode": "preview",
|
||||
"fileSortOrder": "byCreatedTime",
|
||||
"showFrontmatter": true,
|
||||
"autoPairMarkdown": false
|
||||
"autoPairMarkdown": false,
|
||||
"strictLineBreaks": true,
|
||||
"readableLineLength": true
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in a new issue