日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[算法题] Add Two Numbers

發布時間:2025/7/25 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [算法题] Add Two Numbers 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目內容

題目來源:LeetCode

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)
Output: 7 -> 0 -> 8

題目思路

這個題目是倒序存儲了兩個數字,然后模擬進行加法運算。

本題中需要學習到的知識有:

1. 分別使用/和%來代表進位符號flag和當前位的值value

2. 成立啞結點(頭結點),這樣可以方便很多。

Python代碼

# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = Noneclass Solution(object):def addTwoNumbers(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""if not l1 and not l2:returnif not l1:return l2if not l2:return l1dummy=ListNode(-1)p=dummyflag=0while l1 and l2:value=(l1.val+l2.val+flag)%10p.next=ListNode(value)p=p.nextflag=(l1.val+l2.val+flag)/10l1=l1.nextl2=l2.nextwhile l1:value=(l1.val+flag)%10p.next=ListNode(value)p=p.nextflag=(l1.val+flag)/10l1=l1.nextwhile l2:value=(l2.val+flag)%10p.next=ListNode(value)p=p.nextflag=(l2.val+flag)/10l2=l2.nextif flag>0:p.next=ListNode(flag)return dummy.next

?

轉載于:https://www.cnblogs.com/chengyuanqi/p/7136826.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的[算法题] Add Two Numbers的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。