题目要求:
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 contains 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.
解题思路:
- 巧用头指针,本题目也需要使用额外的头指针
- 遍历链表直至为空:while...
- 考虑进位的情况,设置一个标志位。
- 考虑在中间进位和在最后一位进位两种情况。
代码一:
#Time: O(n)
#Space: O(1)
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
current, carry = dummy, 0
while l1 or l2:
val = carry
if l1:
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
carry, val = divmod(val, 10)
current.next = ListNode(val)
current = current.next
if carry == 1:
current.next = ListNode(1)
return dummy.next
补充:Python divmod()函数
- Python 内置函数:divmod()函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。
[>>>11 % 10
1
[>>>12 % 10
2
[>>>2 % 10
2
[>>>11 // 10
1
[>>>11 / 10
1.1
[>>> 12 // 10
1
[>>>12 / 10
1.2
[>>>1 // 10
0
[>>> 1 / 3
0.3333333
[>>>divmod(12,10)
1, 2
[>>>divmod(2,10)
0, 2
网友评论