1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCode. 2.Add Two Numberの回答方法

Posted at

初めに

転職に向けて、LeetCodeを初めてみました。
思っていたより難しかったので、備忘録も兼ねて間違えた問題について、回答方法とその理由を記録していこうと思います(笑)

2.Add Two Numberの回答方法

結論、いかが回答になります。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        tempsum = 0
        root = cur = ListNode(0)
        while l1 or l2 or tempsum:
            if l1:
                tempsum += l1.val
                l1 = l1.next
            if l2:
                tempsum += l2.val
                l2 = l2.next
            cur.next = cur = ListNode(tempsum % 10)
            tempsum //= 10
        return root.next

順を追って解説します。

1.初期化

tempsum = 0
root = cur = ListNode(0)

tempsum は各桁の合計値や繰り上がりを一時的に保存する変数
root は新しく作るリンクリストの ダミーヘッド
cur は現在のノードを指すポインタ(root からスタート)

2.ループ処理

while l1 or l2 or tempsum:

l1 や l2 にまだノードがある、または tempsum に繰り上がりの値が残っている限り続ける。

(1)各ノードをtempsumに加算

if l1:
    tempsum += l1.val
    l1 = l1.next
if l2:
    tempsum += l2.val
    l2 = l2.next

l1 があるなら、その値を tempsum に加算し l1 を次のノードへ
l2 も同様に処理

(2)計算結果の新ノードを作成

cur.next = cur = ListNode(tempsum % 10)
tempsum //= 10

3. 計算が完了したら、新しいリストの先頭を返す

return root.next

最後に

ListNode型のデータを業務で使わないので、何それ美味しいの状態でした(笑)
この問題定期的に見直したい、、

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?