[LeetCode]题解(python):002-Add Two Numbers
题目来源:
https://leetcode.com/problems/add-two-numbers/
题意分析:
这道题目是要将两个单链条相加。输出得到的新链条。
题目思路:
不难发现,其实题目就是要我们模拟加法的实现。那么,我们就直接从低位(链条第一位)开始,同位相加,满10就往高位+1。
代码(python):
# 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 """ ans = ListNode(0) tmp = ans tmpsum = 0 while True: if l1 != None: tmpsum += l1.val l1 = l1.next if l2 != None: tmpsum += l2.val l2 = l2.next tmp.val = tmpsum % 10 tmpsum //= 10 if l1 == None and l2 == None and tmpsum == 0: break tmp.next = ListNode(0) tmp = tmp.next return ans
PS:要注意的是,不要忘记最后的那个+1,比如 1-> 5 + 2->5 = 3-> 0 –> 1
转载请注明出处:http:
/
/
www.cnblogs.com
/
chruny
/