[LeetCode] 2. Add Two Numbers 两个数字相加

落日映苍穹つ 2022-10-02 10:57 215阅读 0赞

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.

Example:

  1. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  2. Output: 7 -> 0 -> 8
  3. Explanation: 342 + 465 = 807.

给定两个链表分别代表两个非负整数。数位以倒序存储,并且每一个节点包含一位数字。将两个数字相加并以链表形式返回。题目不难,主要考察链表操作和加法进位。

进位 = sum / 10,当前位值 = sum % 10

python代码:

  1. class ListNode(object):
  2. def __init__(self, x):
  3. self.val = x
  4. self.next = None
  5. class Solution:
  6. # @return a ListNode
  7. def addTwoNumbers(self, l1, l2):
  8. head = ListNode(0)
  9. l = head
  10. carry = 0
  11. while l1 or l2 or carry:
  12. sum, carry = carry, 0
  13. if l1:
  14. sum += l1.val
  15. l1 = l1.next
  16. if l2:
  17. sum += l2.val
  18. l2 = l2.next
  19. if sum > 9:
  20. carry = 1
  21. sum -= 10
  22. l.next = ListNode(sum)
  23. l = l.next
  24. return head.next
  25. if __name__=='__main__':
  26. a, a.next, a.next.next = ListNode(2), ListNode(4), ListNode(3)
  27. b, b.next, b.next.next = ListNode(5), ListNode(6), ListNode(4)
  28. result = Solution().addTwoNumbers(a, b)
  29. print("{0} -> {1} -> {2}".format(result.val, result.next.val, result.next.next.val))

发表评论

表情:
评论列表 (有 0 条评论,215人围观)

还没有评论,来说两句吧...

相关阅读

    相关 2.相加 Add Two Numbers

    题目描述 给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。如果,我们将这两个数相加起来,则会返回