[LinkedList]002 Add Two Numbers

  • 分类:LinkedList

  • 考察知识点:LinkedList

  • 最优解时间复杂度:**O(n) **

2. Add Two Numbers

  1. 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.
    

代码:

解法:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        res=ListNode(0)
        resp=res
        sum_=0
        p1=l1
        p2=l2
        while(p1!=None or p2!=None):
            if(p1!=None):
                sum_+=p1.val
                p1=p1.next
            if(p2!=None):
                sum_+=p2.val
                p2=p2.next
            resp.next=ListNode(sum_%10)
            sum_//=10
            resp=resp.next
        if sum_==1:
            resp.next=ListNode(1)
            
        return res.next

讨论:

1.太简单的几乎不用懂脑子

002
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 告别斯米兰,我们来到了美丽的普吉,斯米兰是海上最后的“伊甸园”,斯米兰只是普吉的一部分,所以我们要去看一看...
    一只迷路的珠宝师阅读 2,144评论 0 1
  • 提起于盛其人,四九城整个前门这块儿的老少爷们儿没有不知道的。这大名说起来倒是鲜有人听闻,但是架不住人家外号响亮,这...
    寒门士子阅读 3,982评论 0 2
  • 大学毕业等签证那会,每晚在家旁边的河堤散步,一走几个月。在路上,想着各种各样的事情,收获甚多。路很长,却感觉很短。...
    苏柏亚的天空阅读 1,310评论 0 0
  • 在分享幸福的时候我们来一起做一个冥想吧。把眼睛闭上,时间定格在2058年或2068年的今天。 幸福的三大定律: 幸...
    简爸_简书阅读 2,806评论 0 1

友情链接更多精彩内容