首页 > 其他 > 详细

Leetcode #2 Add two number

时间:2016-12-13 08:07:55      阅读:232      评论:0      收藏:0      [点我收藏+]

Q: You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

 
keys: 1. 使用dummy node记录head. 
2. 对于两个list的操作,一般使用 while l1 and l2, if l1, if l2 来处理两个list不一样长的情况。

 1 def addTwoNumbers(l1, l2):
 2 
 3     dummy = cur = NodeList(0)
 4     carry = 0
 5     while l1 and l2:
 6         a = l1.val if l1 else 0
 7         b = l2.val if l2 else 0
 8         sum = a + b + carry
 9         cur.next = ListNode(sum%10)
10         carry = sum/10
11 
12         if l1:
13             cur.next = l1
14         if l2:
15             cur.next = l2
16 
17     if carry > 0:
18         cur.next = ListNode(1)
19 
20     return dummy.next

 

 

Leetcode #2 Add two number

原文:http://www.cnblogs.com/lettuan/p/6168434.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!