2.add two numbers#5
Open
nicah4o wants to merge 1 commit into
Open
Conversation
liquo-rice
reviewed
May 14, 2026
| } | ||
| }; | ||
| ``` | ||
| スタックオーバーフローで上手くいかない。intは10桁、long long型で19桁。 |
| int ten1 = 0; | ||
| while (l1 != nullptr) { | ||
| if (l1->next == nullptr) { | ||
| n1 += l1->val; |
| class Solution { | ||
| public: | ||
| ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | ||
| int n1, n2, n3; |
oda
reviewed
May 14, 2026
| class Solution { | ||
| public: | ||
| ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | ||
| int sum, carry = 0; |
There was a problem hiding this comment.
これ、sum は意図的に初期化しなかったんでしょうか。
個人的には、慣れないうちは一行に一変数にしたほうがいいと思いますね。
| while (l1 || l2 || carry) { | ||
| int v1 = l1 ? l1->val : 0; | ||
| int v2 = l2 ? l2->val : 0; | ||
| sum = v1 + v2 + carry; |
There was a problem hiding this comment.
sum をループ間で受け渡す必要がないので、こっちを int sum にするのも手です。
あ、これは何を言っているかというと、ループを「仕事の引き継ぎ」だと思うと、sum は引き継ぐ必要がないものと感じるということです。
| ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | ||
| int sum, carry = 0; | ||
| ListNode dummy(-1); | ||
| ListNode* node = &dummy; |
There was a problem hiding this comment.
この node はどういう意味でしょうか。このループの中での役割は、主役というよりは「ここまでは確定した結果で、node->next に次の値を書き込む」という役割に見えます。主役でないならば主役でなさそうな名前をつけたほうがいいでしょう。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This problem: https://leetcode.com/problems/add-two-numbers/
Next problem: https://leetcode.com/problems/valid-parentheses/description/