两数相加

2018-10-02  本文已影响0人  3ni

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

# 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
        """
        re = None
        a = l1
        b = l2
        c = re
        yu = 0
        jin = 0
        while a or b:
            t = ListNode(0)
            if re is None:
                re = t
                c = re
            else:
                c.next = t
                c = c.next
            if a and b:
                yu = (a.val + b.val + jin) % 10
                jin = (a.val + b.val + jin) / 10
                c.val = yu
            elif a:
                yu = (a.val + jin) % 10
                jin = (a.val + jin) / 10
                c.val = yu
            elif b:
                yu = (b.val + jin) % 10
                jin = (b.val + jin) / 10
                c.val = yu
            if a:
                a = a.next
            if b:
                b = b.next
        if jin:
            t = ListNode(0)
            c.next = t
            c = c.next
            c.val = jin
        return re

思路:每位上分别相加(比如个位就个位相加,十位就十位相加),注意还要加上低位的进位,所以每位都要记录是否有进位,然后把新生成的位加入一个新的链表,重复这个过程。
注意:要考虑两个链表长度不等,最高位的进位比如(999 + 100 = 1099变成四位数),第一个链表节点的处理方式等

上一篇下一篇

猜你喜欢

热点阅读