반응형
leetcode.com/problems/add-two-numbers/
Solution
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
#include <stdio.h>
#include <malloc.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int sum, carry = 0, val1, val2, num;
struct ListNode* rst_node = 0;
struct ListNode* last_node = 0;
while (1) {
if (l1 != 0) {
val1 = l1->val;
l1 = l1->next;
}
else {
val1 = 0;
}
if (l2 != 0) {
val2 = l2->val;
l2 = l2->next;
}
else {
val2 = 0;
}
sum = val1 + val2 + carry;
carry = sum / 10 == 1 ? 1 : 0;
num = sum % 10;
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->val = num;
new_node->next = 0;
if (rst_node == 0) {
rst_node = new_node;
}
else {
last_node->next = new_node;
}
last_node = new_node;
if (l1 == 0 && l2 == 0 && carry == 0) break;
}
return rst_node;
}
struct ListNode* a = 0;
struct ListNode* b = 0;
void add_a(int value) {
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->val = value;
new_node->next = a;
a = new_node;
}
void add_b(int value) {
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->val = value;
new_node->next = b;
b = new_node;
}
int main() {
add_a(2);
add_a(4);
add_a(3);
add_b(5);
add_b(6);
add_b(4);
struct ListNode* node = addTwoNumbers(a, b);
while (node) {
printf("%d ", node->val);
node = node->next;
}
puts("");
return 0;
}
|
cs |
반응형
'코딩테스트 > Leetcode' 카테고리의 다른 글
Leetcode - [Easy]13. Roman to Integer (0) | 2021.03.14 |
---|---|
Leetcode - [Medium]3. Longest Substring Without Repeating Characters (0) | 2021.03.07 |
Leetcode - [Easy]9. Palindrome Number (0) | 2021.03.04 |
Leetcode - [Easy]7. Reverse Integer (0) | 2021.03.04 |
Leetcode - [Easy]1. Two Sum (0) | 2021.03.04 |