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. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 一直两个很大的数用链表逆序表示。 在例如,1314+520=1834被表示为: # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self,x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self,l1,l2):
""" :type l1: ListNode :type l2: ListNode :rtype: ListNode """
if l1 is None:
return l2
elif l2 is None:
return l1
else:
carry = 0
ret =ListNode(0) #头结点
ret_Last = ret
while(l1 or l2):
sum = 0
if(l1):
sum = l1.val
l1 = l1.next
if(l2):
sum += l2.val
l2 = l2.next
sum += carry #如果有进位则加True(1),否则加False(0)
ret_Last.next = ListNode(sum%10)
ret_Last = ret_Last.next
carry = (sum >= 10) #如果sum>10,则carry表示进位,True被当作1来累加
if(carry):
ret_Last.next =ListNode(1)
ret_Last = ret.next
del ret #删除头结点
return ret_Last
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |