Leetcode学习日记(1)
Leetcode日记(1)
1.题目
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 the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
1 | Input: l1 = [2,4,3], l2 = [5,6,4] |
Example 2:
1 | Input: l1 = [0], l2 = [0] |
Example 3:
1 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
总的来说就是给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。将两个数相加,并以相同形式返回一个表示和的链表。
2.解题思路
- 两个链表分别取数然后相加相加,若某一链表已经为空,则该链表对应的加数置为0。
- 根据和数得到相加后的本位和进位
- 直到历遍两个链表
- 如果进位还是非0,再在链表最后添加一个新的节点
3.代码实现
1 | /** |
4.输出结果
测试用例全部accept
忽略内存占用
本文是原创文章,采用CC BY-NC-SA 4.0协议,完整转载请注明来自Liuylo's blog