2.两数相加

题目描述

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

思路

暴力解,从最低位到最高位依次相加,时间复杂度O(n)

题解

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * 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) {
        ListNode *tail = new (ListNode);
        ListNode *head = tail;
        int cur_bit = 0;
        int carry = 0;
        while (l1 && l2) {
            int sum;
            tail->next = new (ListNode);
            tail = tail->next;
            sum = l1->val + l2->val + carry;
            carry = sum >= 10 ? 1 : 0;
            cur_bit = sum >= 10 ? sum - 10 : sum;
            tail->val = cur_bit;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (l1 == nullptr) {
            while (l2) {
                int sum;
                tail->next = new (ListNode);
                tail = tail->next;
                sum = l2->val + carry;
                carry = sum >= 10 ? 1 : 0;
                cur_bit = sum >= 10 ? sum - 10 : sum;
                tail->val = cur_bit;
                l2 = l2->next;
            }
        } else if (l2 == nullptr) {
            while (l1) {
                int sum;
                tail->next = new (ListNode);
                tail = tail->next;
                sum = l1->val + carry;
                carry = sum >= 10 ? 1 : 0;
                cur_bit = sum >= 10 ? sum - 10 : sum;
                tail->val = cur_bit;
                l1 = l1->next;
            }
        }
        if (carry > 0) {
            tail->next = new (ListNode);
            tail = tail->next;
            tail->val = carry;
        }
        return head->next;
    }
};
Licensed under CC BY-NC-SA 4.0