-
Notifications
You must be signed in to change notification settings - Fork 0
2. Add Two Numbers #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | ||
| ListNode dummy_head = ListNode(); | ||
| ListNode *result_tail = &dummy_head; | ||
| int curry = 0; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
typoしてますね。
| int carry = 0; | ||
| while (l1 || l2 || carry) | ||
| { | ||
| int value = carry; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
変数名 value は一般的すぎて、何の値が入っているのか想像しにくいと感じます。
| value += l2->val; | ||
| l2 = l2->next; | ||
| } | ||
| carry = value / 10; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
処理の始めから value に次々に l1 , l2 の値を足していく処理のようですが、変数の生存期間が長くてなんとなく頭の一時記憶を占める感覚があります。
| ```cpp | ||
| result_tail->next = new ListNode(value); | ||
| ``` | ||
| こんなんしていいの?これ気になった。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
なぜ気になったのか言語化することはできますか?
自分の場合は、関数の中で new で確保したメモリを、誰が解放するのか気になりました。 LeetCode の場合は、プログラムの終了時に OS が解放するのに任せるようです。実務のプログラムではメモリーリークとなるため、原則避けたほうがよいと思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
左辺はresult_tailの指すオブジェクトのListNode型のメンバーにアクセスしていて、new演算子はオブジェクトへのポインタ型(ListNode)を返すので論理的には問題ないかと思います。
|
|
||
| https://leetcode.com/problems/add-two-numbers/description | ||
|
|
||
| C++で書く練習。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
拡張子は、.cc か .cpp にすることが多いです。
あとはいいと思います。
This Problem
https://leetcode.com/problems/add-two-numbers/description
Next Problem
https://leetcode.com/problems/longest-substring-without-repeating-characters/description