Add Two Numbers
问题描述
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
Explanation: 342 + 465 = 807.
算法思路
在这个问题中,有两种解决思路,第一种是先将输入的链表计算结果转换成字符串,再转成链表输出;第二种是直接采用链表操作。总的来说,第一种方法更易于理解,执行效率更高(runtime is 116ms),第二种方法更加复杂,耗时更长(runtime is 288ms),所以推荐使用方法一。
代码实现(Python3)
方法一:
1 |
|
方法二:
1 |
|
参考资料
- https://stackoverflow.com/questions/31633635/what-is-the-meaning-of-inta-1-in-python What is the meaning of “int(a[::-1])” in Python?
- https://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list-in-python Getting the last element of a list in Python
- https://www.pythoncentral.io/pythons-range-function-explained/ Python’s range() Function Explained
- https://leetcode.com/problems/add-two-numbers/ Add Two Numbers
Add Two Numbers
https://xiepeng21.cn/posts/64c8f80f/