码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode #2 Add two number

时间:2016-12-13 08:10:34      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:log   tor   pre   tco   while   res   node   mon   leetcode   

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

标签:log   tor   pre   tco   while   res   node   mon   leetcode   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!