Skip to content

2.Add Two Numbers#5

Open
yus-yus wants to merge 2 commits intomainfrom
2.Add-Two-Numbers
Open

2.Add Two Numbers#5
yus-yus wants to merge 2 commits intomainfrom
2.Add-Two-Numbers

Conversation

@yus-yus
Copy link
Copy Markdown
Owner

@yus-yus yus-yus commented Feb 4, 2025

@X-XsleepZzz
Copy link
Copy Markdown

読みやすくて良かったです!

Comment on lines +133 to +134
digit = total % 10
carry = total // 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.

このように書く方法もあるようです。
carry, digit = divmod(total, 10)

これがいいとというより、選択肢の一つとしてご紹介です。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。
その組み込み関数は知りませんでした。勉強になります。
使いどころが限定されてそうですが今回の問題にはピッタリですね。


while carry != 0 or l1 is not None or l2 is not None:
total = carry

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

if not l1:
    l1 = ListNode(0)
if not l2:
    l2 = ListNode(0)

という番兵を使う手があります。

ここの方法の応用です。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.cxy3cik6kyqx

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。
Noneの時は0埋めするということですね。実装してみました。

total = l1.val + l2.val + carry

と書けるのが良いです。
新たにListNodeを追加してしまいますが、どのような使われ方をするか見て問題なさそうであれば変なリスクは取らずに可読性を優先するということですね。

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.

4 participants