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:

img

1
2
3
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

1
2
Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

1
2
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

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.解题思路

  1. 两个链表分别取数然后相加相加,若某一链表已经为空,则该链表对应的加数置为0。
  2. 根据和数得到相加后的本位和进位
  3. 直到历遍两个链表
  4. 如果进位还是非0,再在链表最后添加一个新的节点

3.代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode* l3 = new ListNode();
ListNode* p = l3;

while (l1 != nullptr || l2 != nullptr) {
int a1 = (l1 != nullptr) ? l1->val : 0;
int a2 = (l2 != nullptr) ? l2->val : 0;

int sum = a1 + a2 + carry;
carry = sum / 10;
int digit = sum % 10;

p->next = new ListNode(digit);
p = p->next;

if (l1 != nullptr) l1 = l1->next;
if (l2 != nullptr) l2 = l2->next;
}

if (carry > 0) {
p->next = new ListNode(carry);
}

return l3->next;
}
};

4.输出结果

测试用例全部accept

image

忽略内存占用