[LinkedList]002 Add Two Numbers

  • 分類:LinkedList

  • 考察知識點:LinkedList

  • 最優(yōu)解時間復(fù)雜度:**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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,857評論 0 10
  • 告別斯米蘭,我們來到了美麗的普吉,斯米蘭是海上最后的“伊甸園”,斯米蘭只是普吉的一部分,所以我們要去看一看...
    一只迷路的珠寶師閱讀 315評論 0 1
  • 提起于盛其人,四九城整個前門這塊兒的老少爺們兒沒有不知道的。這大名說起來倒是鮮有人聽聞,但是架不住人家外號響亮,這...
    寒門士子閱讀 777評論 0 2
  • 大學(xué)畢業(yè)等簽證那會,每晚在家旁邊的河堤散步,一走幾個月。在路上,想著各種各樣的事情,收獲甚多。路很長,卻感覺很短。...
    蘇柏亞的天空閱讀 194評論 0 0
  • 在分享幸福的時候我們來一起做一個冥想吧。把眼睛閉上,時間定格在2058年或2068年的今天。 幸福的三大定律: 幸...
    簡爸_簡書閱讀 391評論 0 1

友情鏈接更多精彩內(nèi)容