[Leetcode]2.Add Two Numbers @python

来源:互联网 发布:055 知乎 编辑:程序博客网 时间:2024/05/02 04:46

题目

You are given two linked lists representing two non-negative numbers. 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.

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

解题思路

这道题看起来很简单,但是我用的方法效率并不是特别高,暂且贴在这里,欢迎大家指正.

class Solution(object):    def addTwoNumbers(self, l1, l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        if l1 == None or l2 == None:            return l1 if l1 else l2        ans,pre = l1,l1        c = 0        while l1 and l2:            t = l1.val + l2.val + c            c,l1.val = t / 10, t % 10            pre = l1            l1,l2 = l1.next,l2.next        remain = l1 if l1 != None else l2        if remain != None:            pre.next = remain            while remain and c > 0:                t = c + remain.val                c,remain.val = t / 10,t % 10                pre,remain = remain,remain.next        if c > 0:            pre.next = ListNode(c)        return ans
0 0