2. Add Two Numbers#5
Open
rimokem wants to merge 1 commit into
Open
Conversation
liquo-rice
reviewed
Mar 26, 2026
Comment on lines
+15
to
+16
| node1 = l1 | ||
| node2 = l2 |
There was a problem hiding this comment.
新しい変数に置く必要はなさそうです。変数名がheadとかですと、動かすと、意味と名前が一致しなくなるので、避ける方が望ましいですが、この場合ですと、そのまま動かした方がいいかなと。
|
|
||
| - 繰り上げは真偽値がよいと思っていたが、3つ以上の数の和を考えると数値が自然 | ||
| - コードも簡潔になる | ||
| - ループ条件に`carry != 0`を使っている解答もあるが、個人的には抜けた後に処理した方が意図がわかりやすいと思う。 |
There was a problem hiding this comment.
2つのリストの足し算だったら、最大でも一桁しか位は上がりませんが、3個以上のリストの足し算とかだと、話が変わってくるので、whileに含めた方がより一般的なケースに対応できそうですね。同じ処理を複数箇所に書かなくて良いですし。
| - コードも簡潔になる | ||
| - ループ条件に`carry != 0`を使っている解答もあるが、個人的には抜けた後に処理した方が意図がわかりやすいと思う。 | ||
| - `divmod`を使えば、商と余りが同時に得られる。 | ||
| - (自分は知らなかったので)可読性が低いかとも思ったが、関数名と変数名から想像できる範囲だと思ったので採用。 |
There was a problem hiding this comment.
標準ライブラリや組み込み関数を正しく使って可読性が下がることはなさそうです。知らない人が多いのと、可読性はまた別の概念かなと。
| @@ -0,0 +1,95 @@ | |||
| # 2. Add Two Numbers | |||
|
|
|||
| ## step1 | |||
There was a problem hiding this comment.
in-placeでやる方法もありますね。空間計算量O(1)でやってくださいとか指定されたりするかもしれません。
| carry, digit = divmod(value1 + value2 + carry, 10) | ||
| sum_node.next = ListNode(digit) | ||
|
|
||
| node1 = node1.next if node1 is not None else None |
h-masder
reviewed
Mar 26, 2026
| value2 = node2.val if node2 is not None else 0 | ||
|
|
||
| sum_value = value1 + value2 + (1 if has_carry else 0) | ||
| sum_node.next = ListNode(sum_value % 10) |
There was a problem hiding this comment.
has_carryを数値で保持して、
sum_value = value1 + value 2 + has_carry
sum_node.next = ListNode(val=sum_value % 10)とすると、3個以上のリストの足し算にも対応できそうです。
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.
今回の問題
https://leetcode.com/problems/add-two-numbers/description/
次回の問題
https://leetcode.com/problems/valid-parentheses/description/