LeetCode2:Add Two Numbers

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:

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

LeetCode:链接

有两个链表,分别是逆序了的十进制数字。现在要求两个十位数字的和,要求返回的结果也是链表。

可以采用一个进位carry方便的完成一次遍历得出结果。

æ­¤å¤è¾å¥å¾ççæè¿°

两个要注意的地方:如果列表长度不相等;如果列表相加完成最后仍有进位位。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        dummy = head
        # 进位标志
        carry = 0
        while l1 and l2:
            add = l1.val + l2.val + carry
            # 是否有进位
            carry = 1 if add >= 10 else 0
            # 必须是定义一个结点
            dummy.next = ListNode(add % 10)
            dummy = dummy.next
            l1, l2 = l1.next, l2.next
        # 如果列表长度不相等
        l = l1 if l1 else l2
        while l:
            add = l.val + carry
            carry = 1 if add >= 10 else 0
            dummy.next = ListNode(add % 10)
            dummy = dummy.next
            l = l.next
        # 如果列表相加完成最后仍有进位位
        if carry:
            dummy.next = ListNode(1)
        return head.next

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/85624487
今日推荐