leetcode 【 Add Two Numbers 】 python 实现
题目:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
代码:oj测试通过 Runtime: 171 ms
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @return a ListNode 9 def addTwoNumbers(self, l1, l2): 10 if l1 is None: 11 return l2 12 if l2 is None: 13 return l1 14 15 dummyhead = ListNode(0) 16 p = ListNode(0) 17 dummyhead.next = p 18 19 jinwei = 0 20 while l1 is not None and l2 is not None: 21 curr_total = l1.val + l2.val + jinwei 22 l1 = l1.next 23 l2 = l2.next 24 curr_digit = curr_total % 10 25 jinwei = curr_total / 10 26 curr_node = ListNode(curr_digit) 27 p.next = curr_node 28 p = p.next 29 30 if l1 is not None: 31 while l1 is not None: 32 curr_total = l1.val + jinwei 33 l1 = l1.next 34 curr_digit = curr_total % 10 35 jinwei = curr_total / 10 36 curr_node = ListNode(curr_digit) 37 p.next = curr_node 38 p = p.next 39 if l2 is not None: 40 while l2 is not None: 41 curr_total = l2.val + jinwei 42 l2 = l2.next 43 curr_digit = curr_total % 10 44 jinwei = curr_total / 10 45 curr_node = ListNode(curr_digit) 46 p.next = curr_node 47 p = p.next 48 49 if jinwei == 1: 50 curr_node = ListNode(1) 51 p.next = curr_node 52 53 return dummyhead.next.next
思路:
就是加法运算 注意两条链表上所有值计算过后 是否有进位;如果有进位 需要再处理一下。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?