-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2. Add Two Numbers.c
More file actions
56 lines (49 loc) · 1.34 KB
/
2. Add Two Numbers.c
File metadata and controls
56 lines (49 loc) · 1.34 KB
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
// https://leetcode.com/problems/add-two-numbers/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdlib.h>
#include <assert.h>
struct ListNode *mk_node(int val, struct ListNode *nxt) {
struct ListNode *res = malloc(sizeof(struct ListNode));
res->val = val;
res->next = nxt;
return res;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
assert(l1);
assert(l2);
struct ListNode *res = mk_node((l1->val + l2->val) % 10, NULL);
int carry = (l1->val + l2->val) / 10;
l1 = l1->next;
l2 = l2->next;
struct ListNode *cur = res;
while (l1 || l2) {
if (!l1) {
int total = l2->val + carry;
cur->next = mk_node(total % 10, NULL);
carry = total / 10;
l2 = l2->next;
} else if (!l2) {
int total = l1->val + carry;
cur->next = mk_node(total % 10, NULL);
carry = total / 10;
l1 = l1->next;
} else {
int total = l1->val + l2->val + carry;
cur->next = mk_node(total % 10, NULL);
carry = total / 10;
l1 = l1->next;
l2 = l2->next;
}
cur = cur->next;
}
if (carry) {
cur->next = mk_node(1, NULL);
}
return res;
}