python两个数相加时_两数相加 leetcode Python
給定兩個非空鏈表來表示兩個非負整數(shù)。位數(shù)按照逆序方式存儲,它們的每個節(jié)點只存儲單個數(shù)字。將兩數(shù)相加返回一個新的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個數(shù)字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
isFirst = True
currentNode = None
head = None
while(l1 or l2 or carry != 0):
val1 = 0
val2 = 0
if l1:
val1 = l1.val
l1 = l1.next
if l2:
val2 = l2.val
l2 = l2.next
sum = val1 + val2 + carry
if sum >= 10:
carry = 1
sum = sum % 10
else:
carry = 0
node = ListNode(sum)
if isFirst:
currentNode = node
head = currentNode
isFirst = False
else:
currentNode.next = node
currentNode = currentNode.next
return head
總結(jié)
以上是生活随笔為你收集整理的python两个数相加时_两数相加 leetcode Python的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql自动生成日期序列号_mysql
- 下一篇: python迭代法求解非线性方程_荐【数