今天的题目是两数相加。
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.
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
My answer:
首先创建两个指针指向结果链表的头节点,一个指针dummy始终指在头节点,一个指针now用来指向尾结点(新值插入的位置)。然后设置一个进位标志carry初始化为0。x来代表l1的数值,y代表l2数值,任意一个链表的结束时其对应数值设为0,直到两个链表均结束循环停止。然后在循环内,获得当前位的值sum = x+y+carry和进位carry = sum//10,并将新值sum%10接在now指针后面。最后循环结束时,判断是否依然有进位,如果有进位则在结果链表后新增值为1的结点即可。最后返回dummy.next(注意返回时略过头节点)链表。
Runtime: 40 ms, faster than 99.89% of Python online submissions for Add Two Numbers.
Memory Usage: 11.9 MB, less than 31.51% of Python online submissions for Add Two Numbers.
# 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
"""
now = dummy = ListNode(0) #new node
carry = 0
while(l1 or l2):
x = l1.val if l1 is not None else 0
y = l2.val if l2 is not None else 0
sum = x+y+carry
carry = sum//10
now.next = ListNode(sum%10)
now = now.next
if(l1): l1 = l1.next
if(l2): l2 = l2.next
if(carry):
now.next = ListNode(1)
return dummy.next
全部0条评论
快来发表一下你的评论吧 !