Skip to content

Commit

Permalink
Add two numbers
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 11, 2017
1 parent e478f76 commit 3ff4e56
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 2_add_two_numbers/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test add_two_numbers.c
100 changes: 100 additions & 0 deletions 2_add_two_numbers/add_two_numbers.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Definition for singly-linked list. */
struct ListNode {
int val;
struct ListNode *next;
};

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int carry_num = 0;
int first = 1;
struct ListNode *res = NULL;
struct ListNode *p = NULL;
struct ListNode *prev = p;

while (l1 != NULL || l2 != NULL || carry_num) {
int sum = 0;
int last_carry = carry_num;
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
if (sum >= 10) {
sum -= 10;
carry_num = 1;
} else {
carry_num = 0;
}

p = malloc(sizeof(*p));
if (first) {
res = p;
first = 0;
}
p->val = sum + last_carry;
if (p->val >= 10) {
p->val -= 10;
carry_num = 1;
}
p->next = NULL;
if (prev != NULL) {
prev->next = p;
}
prev = p;
}

return res;
}

static struct ListNode *node_build(const char *digits)
{
struct ListNode *res, *p, *prev;
int first = 1;
int len = strlen(digits);
const char *c = digits + len - 1;
prev = NULL;
while (len-- > 0) {
p = malloc(sizeof(*p));
if (first) {
first = 0;
res = p;
}
p->val = *c-- - '0';
p->next = NULL;
if (prev != NULL) {
prev->next = p;
}
prev = p;
}

return res;
}

static void show(struct ListNode *ln)
{
int sum = 0, factor = 1;
while (ln != NULL) {
sum += ln->val * factor;
factor *= 10;
ln = ln->next;
}
printf("%d\n", sum);
}

int main(int argc, char **argv)
{
struct ListNode *l1 = node_build(argv[1]);
struct ListNode *l2 = node_build(argv[2]);
struct ListNode *res = addTwoNumbers(l1, l2);
show(l1);
show(l2);
show(res);
return 0;
}
Binary file removed median_of_two_sorted_array/test
Binary file not shown.

0 comments on commit 3ff4e56

Please sign in to comment.