Skip to content

2. Add Two Numbers#5

Open
rimokem wants to merge 1 commit into
mainfrom
0002-add-two-numbers
Open

2. Add Two Numbers#5
rimokem wants to merge 1 commit into
mainfrom
0002-add-two-numbers

Conversation

@rimokem
Copy link
Copy Markdown
Owner

@rimokem rimokem commented Mar 26, 2026

Comment thread 0002/memo.md
Comment on lines +15 to +16
node1 = l1
node2 = l2
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

新しい変数に置く必要はなさそうです。変数名がheadとかですと、動かすと、意味と名前が一致しなくなるので、避ける方が望ましいですが、この場合ですと、そのまま動かした方がいいかなと。

Comment thread 0002/memo.md

- 繰り上げは真偽値がよいと思っていたが、3つ以上の数の和を考えると数値が自然
- コードも簡潔になる
- ループ条件に`carry != 0`を使っている解答もあるが、個人的には抜けた後に処理した方が意図がわかりやすいと思う。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2つのリストの足し算だったら、最大でも一桁しか位は上がりませんが、3個以上のリストの足し算とかだと、話が変わってくるので、whileに含めた方がより一般的なケースに対応できそうですね。同じ処理を複数箇所に書かなくて良いですし。

Comment thread 0002/memo.md
- コードも簡潔になる
- ループ条件に`carry != 0`を使っている解答もあるが、個人的には抜けた後に処理した方が意図がわかりやすいと思う。
- `divmod`を使えば、商と余りが同時に得られる。
- (自分は知らなかったので)可読性が低いかとも思ったが、関数名と変数名から想像できる範囲だと思ったので採用。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

標準ライブラリや組み込み関数を正しく使って可読性が下がることはなさそうです。知らない人が多いのと、可読性はまた別の概念かなと。

Comment thread 0002/memo.md
@@ -0,0 +1,95 @@
# 2. Add Two Numbers

## step1
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in-placeでやる方法もありますね。空間計算量O(1)でやってくださいとか指定されたりするかもしれません。

Comment thread 0002/memo.md
carry, digit = divmod(value1 + value2 + carry, 10)
sum_node.next = ListNode(digit)

node1 = node1.next if node1 is not None else None
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2回同じチェックをしているのでまとめても良いですね。

Comment thread 0002/memo.md
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)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

has_carryを数値で保持して、

sum_value = value1 + value 2 + has_carry
sum_node.next = ListNode(val=sum_value % 10)

とすると、3個以上のリストの足し算にも対応できそうです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants