您的位置:首页 > 编程语言 > Python开发

(python)leetcode刷题笔记 02 Add Two Numbers

2018-01-03 19:39 661 查看

2. 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.


# Definition for singly-linked list.
#class ListNode:
#    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
"""
if l1==None:
return l2
if l2==None:
return l1
carry=0
s=ListNode(0)
ret=s
while l1 or l2:#如果两个链表next均不为空
sum=0
if l1:
sum+=l1.val
l1=l1.next
if l2:
sum+=l2.val
l2=l2.next
sum+=carry
s.next=ListNode(sum%10)
s=s.next
carry=(sum>=10)
if carry==1:
s.next=ListNode(1)
del s
return ret.next


ANSWER
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: