[LeetCode] 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.
给定两个链表分别代表两个非负整数。数位以倒序存储,并且每一个节点包含一位数字。将两个数字相加并以链表形式返回。题目不难,主要考察链表操作和加法进位。
进位 = sum / 10,当前位值 = sum % 10
python代码:
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
head = ListNode(0)
l = head
carry = 0
while l1 or l2 or carry:
sum, carry = carry, 0
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
if sum > 9:
carry = 1
sum -= 10
l.next = ListNode(sum)
l = l.next
return head.next
if __name__=='__main__':
a, a.next, a.next.next = ListNode(2), ListNode(4), ListNode(3)
b, b.next, b.next.next = ListNode(5), ListNode(6), ListNode(4)
result = Solution().addTwoNumbers(a, b)
print("{0} -> {1} -> {2}".format(result.val, result.next.val, result.next.next.val))
还没有评论,来说两句吧...