2017年7月13日 星期四

LeetCode題解 - 2. Add Two Numbers [Medium]

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

1. Code:
  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution(object):
  8. def addTwoNumbers(self, l1, l2):
  9. """
  10. :type l1: ListNode
  11. :type l2: ListNode
  12. :rtype: ListNode
  13. """
  14. rtype = None
  15. prev = None
  16. plugs = 0
  17.  
  18. while (l1 is not None) or (l2 is not None) or plugs != 0:
  19. v1 = self._getListNodeValue(l1)
  20. v2 = self._getListNodeValue(l2)
  21. l1 = self._getNextListNode(l1)
  22. l2 = self._getNextListNode(l2)
  23. count = v1 + v2 + plugs
  24. plugs = count / 10
  25. ln = ListNode(count % 10)
  26. if rtype is None:
  27. rtype = ln
  28. prev = rtype
  29. else:
  30. prev.next = ln
  31. prev = prev.next
  32. return rtype
  33. def _getListNodeValue(self, ln):
  34. """
  35. :type l1: ListNode
  36. :rtype: number
  37. """
  38. if not isinstance(ln, ListNode):
  39. return 0
  40. return ln.val
  41. def _getNextListNode(self, ln):
  42. """
  43. :type l1: ListNode
  44. :rtype: ListNode
  45. """
  46. if not isinstance(ln, ListNode):
  47. return None
  48. return ln.next

心得:
一看見題目就覺得簡單啊,刷刷地就寫完了
點Run Code按鈕,嗯?怎麼會出現這種錯誤訊息
重新看一次題目,原來有定義一個class ListNode
我還以為會傳進來的是List…

用Python寫Link-list,雖然不是不行拉



應該是防呆機制的關係,拿掉再試乙次

2. Code:
  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution(object):
  8. def addTwoNumbers(self, l1, l2):
  9. """
  10. :type l1: ListNode
  11. :type l2: ListNode
  12. :rtype: ListNode
  13. """
  14. rtype = None
  15. prev = None
  16. plugs = 0
  17.  
  18. while (l1 is not None) or (l2 is not None) or plugs != 0:
  19. v1 = v2 = 0
  20. if l1 is not None:
  21. v1 = l1.val
  22. l1 = l1.next
  23. if l2 is not None:
  24. v2 = l2.val
  25. l2 = l2.next
  26. count = v1 + v2 + plugs
  27. plugs = count / 10
  28. ln = ListNode(count % 10)
  29. if rtype is None:
  30. rtype = ln
  31. prev = rtype
  32. else:
  33. prev.next = ln
  34. prev = prev.next
  35. return rtype

心得:
速度快了一點吧,微妙


沒有留言:

張貼留言