#2. Add Two Numbers

上一篇 / 下一篇  2017-07-25 01:03:22 / 个人分类:leetcode

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
# 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.
#
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = []
tmp = 0
while l1 or l2 or tmp:
if not l1:
value1 = 0
l1 = None
else:
value1 = l1.val
l1 = l1.next
if not l2:
value2 = 0
l2 = None
else:
value2 = l2.val
l2 = l2.next
result.append((value1 + value2 + tmp)%10)
tmp = (value1 + value2 + tmp)//10
return result

if __name__ == '__main__':

a = ListNode(2)
a.next = ListNode(4)
a.next.next = ListNode(3)
b = ListNode(5)
b.next = ListNode(6)
b.next.next = ListNode(4)

result = Solution().addTwoNumbers(a, b)
print(result)

TAG: leetcode

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar