Re: [閒聊] 每日leetcode已回收
看板Marginalman作者sustainer123 (caster )時間1年前 (2024/05/07 14:05)推噓2(2推 0噓 1→)留言3則, 3人參與討論串197/1548 (看更多)
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言:
: https://leetcode.com/problems/double-a-number-represented-as-a-linked-list/description
: 2816. Double a Number Represented as a Linked List
: 給你一個鏈結串列表示的十進位數,把他乘以二並且一樣用鏈結串列表示。
: 思路:
: 1.遞迴鏈結串列,如果有進位就返回一個包含進位的node,如果沒進位就返回null。
: pycode:
: ---------------------------------------
: class Solution:
: def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
: def dfs(root: Optional[ListNode]) -> ListNode:
: if not root:
: return None
: root.val *= 2
: carry = dfs(root.next)
: if carry:
: root.val += carry.val
: if root.val > 9:
: root.val %= 10
: return ListNode(1, root)
: else:
: return None
: node = dfs(head)
: return node if node else head
: ---------------------------------------
思路:
分成兩種狀況
1.首位數字假如>5 代表需要插入新的node
2.其他 看下一位數是否需要進位 需進位就加1
Python Code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
tmp = 0
if head.val >= 5:
head = ListNode(1,head)
cur = head.next
pre = (cur.val * 2) %10
else:
cur = head
pre = cur.val * 2
while cur:
if cur.next:
tmp = cur.next.val *2
if tmp > 9:
pre += 1
tmp = tmp % 10
cur.val = pre
pre = tmp
cur = cur.next
return head
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.170.119 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715061944.A.251.html
→
05/07 14:07,
1年前
, 1F
05/07 14:07, 1F
推
05/07 14:07,
1年前
, 2F
05/07 14:07, 2F
推
05/07 14:08,
1年前
, 3F
05/07 14:08, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 197 之 1548 篇):