看板 Marginalman 關於我們 聯絡資訊
※ 引述《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 : --------------------------------------- 思路: 先檢查下一個node會不會進位,有的話這個node要+1 C# code public class Solution { public ListNode DoubleIt(ListNode head) { var current = head; if (head.val >= 5) { head = new ListNode(1, head); } while (current != null) { current.val = current.val * 2 % 10; if (current.next != null && current.next.val >= 5) { current.val++; } current = current.next; } return head; } } -- (づ′・ω・)づ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.96.37 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715045847.A.689.html