首页 > 代码库 > leetcode 【 Add Two Numbers 】 python 实现
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 l212 if l2 is None:13 return l114 15 dummyhead = ListNode(0)16 p = ListNode(0)17 dummyhead.next = p18 19 jinwei = 020 while l1 is not None and l2 is not None:21 curr_total = l1.val + l2.val + jinwei22 l1 = l1.next23 l2 = l2.next24 curr_digit = curr_total % 1025 jinwei = curr_total / 1026 curr_node = ListNode(curr_digit)27 p.next = curr_node28 p = p.next29 30 if l1 is not None:31 while l1 is not None:32 curr_total = l1.val + jinwei33 l1 = l1.next34 curr_digit = curr_total % 1035 jinwei = curr_total / 1036 curr_node = ListNode(curr_digit)37 p.next = curr_node38 p = p.next39 if l2 is not None:40 while l2 is not None:41 curr_total = l2.val + jinwei42 l2 = l2.next43 curr_digit = curr_total % 1044 jinwei = curr_total / 1045 curr_node = ListNode(curr_digit)46 p.next = curr_node47 p = p.next48 49 if jinwei == 1:50 curr_node = ListNode(1)51 p.next = curr_node52 53 return dummyhead.next.next
思路:
就是加法运算 注意两条链表上所有值计算过后 是否有进位;如果有进位 需要再处理一下。
leetcode 【 Add Two Numbers 】 python 实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。