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

2. Add Two Numbers

时间:2018-09-25 16:11:22      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:题目   else   lead   inpu   ber   top   may   tput   eve   

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.



class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None:
            return l1
        elif l2 is None:
            return l1
        start = ListNode(0)
        temp = start
        carry = 0
        while l1 or l2:
            sum = 0
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            sum += carry
            carry = 1 if sum>9 else 0
            temp.next = ListNode(sum % 10)
            temp = temp.next
        if carry:
            temp.next = ListNode(1)
        temp = start.next
        del start
        return temp

链表题目,发现已经忘记怎么用链表了。。这道题用头结点会简单很多

 

ps.说来惭愧,很久没有刷过题了,再忙也不应该成为不刷题的借口,于是从今日立下flag,每天刷五道题。

 

2. Add Two Numbers

标签:题目   else   lead   inpu   ber   top   may   tput   eve   

原文地址:https://www.cnblogs.com/bernieloveslife/p/9699838.html

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