Python 解leetcode:2. Add Two Numbers
题目描述:输入两个非空单链表,链表的每个结点的值是一个1位数整数,两个链表都是一个大整数每一位的逆序排序,求这两个链表代表的整数的和的链表值;
思路:
- 分别遍历两个链表,转化成相应的整数,求和后把结果每一位转化成单链表即可;
python">class Solution(object): def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
a = b = 0
carry = 0
while l1:
a += l1.val * 10 ** carry
carry += 1
l1 = l1.next
carry = 0
while l2:
b += l2.val * 10 ** carry
carry += 1
l2 = l2.next
ret = a + b
h = m = ListNode(0)
if not ret:
return h
while ret:
m.next = ListNode(ret % 10)
ret /= 10
m = m.next
return h.next
以上是 Python 解leetcode:2. Add Two Numbers 的全部内容, 来源链接: utcz.com/z/388706.html