Problem Description:
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.
Accepted
674,384
Submissions
2,266,721
这是对python链表的考察 在代码段中提示使用python链表。
其中用到 divmod
divmod(x,y)
return (x//y, x%y)
# 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
"""
# 首先初始化一个链表用于存放结果
result = p = ListNode(0)
# 定义加法进位
carry = 0
# 定义接受位 用于接收了l1 l2的数值进行相加运算
v1 = v2 = 0
# 用于接收相加产生的结果 存进新的链表
val = 0
while l1 or l2 or carry:
# if l1 is None:
# return l2
# if l2 is None:
# return l1
# 初始化v1 v2 防止带着上次的值加上去
v1 = v2 = 0
# 取l1 l2的各项相加
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2= l2.next
carry, val = divmod(v1+v2+carry, 10) # 要记得开辟新的结点
p.next = ListNode(val)
p = p.next
p.next = None
return result.next
'''
Input
[5]
[5]
Output
[0]
Expected
[0,1]
1、未考虑 进位 不为零的情况 5 + 5 = 1 0 此时 l1 l2 皆空了 但是还有进位未加上去
2、不过考虑到此 同时还忘了每次初始化 v1 v2 不然在这种情况下 v1 v2 会带着上次的值
加上去
'''