LeetCode2 两数相加
程序员文章站
2022-04-04 09:03:20
...
题目描述
该题为中等难度,链表、进位
解题
# 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
"""
l3 = ListNode(0)
r = l3
p = l1
q = l2
carry = 0
temp = 0
while (p or q):
if not p:
val1 = 0
else:
val1 = p.val
if q:
val2 = q.val
else:
val2 = 0
temp = val1+val2+carry
carry = temp/10
val = temp%10
r.next = ListNode(val)
if p:
p=p.next
if q:
q = q.next
r = r.next
if carry!=0:#最后的进位
r.next = ListNode(1)
return l3.next
上一篇: 再次狂欢不容错过 双十二值得购买手机推荐
下一篇: 【Leetcode2】两数相加