[LeetCode]#2 Add Two Numbers

一、题目

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

 

二、解析

本题是大数加法,用Python不用考虑数据类型的问题。另外题中的逆序也并不产生什么影响,输入逆序,输出也是逆序,直接从0开始即可。

 

三、实现思路

1.建立一个链表,作为最终输出结果

2.取出L1,L2相同位置的数,与进位一起加和得tempSum。%作为本位值thisValue,/作为下一位的进位nextExtra

3.若加和过程中L1或者L2为None,则说明这个链表已到头,加和时用0做替补。

 

四、难点

1.while循环的退出条件需要整体考虑后才能确定是三项:L1,L2和nextExtra

2.Python链表操作

 

五、Python代码

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # @param {ListNode} l1
 9     # @param {ListNode} l2
10     # @return {ListNode}
11     def addTwoNumbers(self, l1, l2):
12         LinkList = p = ListNode(0)
13         nextExtra = 0
14         
15         while l1 or l2 or nextExtra:
16             if l1:
17                 temp1 = l1.val
18             else:
19                 temp1 = 0
20             
21             if l2:
22                 temp2 = l2.val
23             else:
24                 temp2 = 0
25             
26             tempSum = temp1 + temp2 + nextExtra
27             thisValue = tempSum % 10
28             nextExtra = tempSum / 10
29             
30             p.next = ListNode(thisValue)
31             p = p.next
32             if l1:
33                 l1 = l1.next
34             if l2:
35                 l2 = l2.next
36         
37         return LinkList.next

 

六、总结

1.在本题中,了解了Python中链表的方法。用class来定义一个数据类型,与C语言相比更好用,另外代码中的l1,l2都是指针,不带*使代码看起来十分简洁。

2.链表连续声明LinkList = p = ListNode(),这里p,LinkList都是表示一个链表,只是这里p用于执行向后移位添加元素,LinkList一直指向链表的开始。还是指针的用法,但就是感觉好好用。

3.之前用C语言实现过大数相加,要将int转换成str。一见这题第一反应是要转换成str,被误导了一会儿,看了别人的代码后才回过神来。

4.效率不高,执行了202ms,排在中间,和同学讨论一下哪里可以优化。

5.有的时候那些最快的算法往往都是根据本题具体要求设计的“取巧”算法,这方面还需要锻炼,具体问题具体分析,得出最优结果,应该还有很长的路要走。

6.没有了,加油!

 

posted @ 2015-06-30 16:24  面包包包包包包  阅读(154)  评论(0编辑  收藏  举报