Add Two Number

https://oj.leetcode.com/problems/add-two-numbers/

Add Two Number

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

题目:两个链表代表的两个数字相加,逆向表示。

 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         if l1==None:return l2                     #在最开始的时候,其中有任意的值为空,即个位数都为空,相加直接返回另一个数
13         if l2==None:return l1
14         dummy=ListNode(0)
15         p=dummy
16         flag=0                                    #对进位的计数
17         while l1 and l2:
18             p.next=ListNode((l1.val+l2.val+flag)%10)
19             flag=(l1.val+l2.val+flag)/10
20             l1=l1.next;l2=l2.next;p=p.next
21         if l1:                                    #当前面的while l1和l2每一位都不为空结束时,若l1较长还有高数位的数,l2已为空时
22             while l1:
23                 p.next=ListNode((l1.val+flag)%10)
24                 flag=(l1.val+flag)/10
25                 l1=l1.next;p=p.next
26         if l2:                                    #l2比l1位数更多时
27             while l2:
28                 p.next=ListNode((l2.val+flag)%10)
29                 flag=(l2.val+flag)/10
30                 l2=l2.next;p=p.next
31         if flag==1:                               #最终还有一个进位时
32             p.next=ListNode(1)
33         return dummy.next

 

posted @ 2015-06-28 13:52  小榛子  阅读(221)  评论(0编辑  收藏  举报