# LeetCode 2. Add Two Numbers

250人阅读 评论(0)

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

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

class Solution(object):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res=[(l1.val+l2.val)%10]
kes=[(l1.val+l2.val)/10]
l1=l1.next
l2=l2.next
k=1
while(l1 != None and l2 !=None):    #l1 与 l2 均未遍历完
res.append((l1.val+l2.val+kes[k-1])%10)
kes.append((l1.val+l2.val+kes[k-1])/10)
k+=1
l1=l1.next
l2=l2.next
while(l1 !=None and l2 == None):    #l1 比 l2长时
res.append((l1.val+kes[k-1])%10)
kes.append((l1.val+kes[k-1])/10)
k+=1
l1=l1.next
while(l1 ==None and l2 != None):    #l2 比 l1长时
res.append((l2.val+kes[k-1])%10)
kes.append((l2.val+kes[k-1])/10)
k+=1
l2=l2.next
if kes[k-1]>0:               #链表最后一位处理
res.append(kes[k-1]%10)
return res

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：9026次
• 积分：516
• 等级：
• 排名：千里之外
• 原创：80篇
• 转载：3篇
• 译文：0篇
• 评论：2条
文章分类
阅读排行
评论排行
最新评论