-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDAY0010.cpp
More file actions
63 lines (63 loc) · 1.51 KB
/
DAY0010.cpp
File metadata and controls
63 lines (63 loc) · 1.51 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
57
58
59
60
61
62
63
// 2. Add Two Numbers
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode answerlist;
struct ListNode *answer=&answerlist;
int carry=0;
while(l1!=NULL&&l2!=NULL){
if((l1->val+l2->val+carry)>=10){
l1->val=(l1->val+l2->val+carry)-10;
carry=1;
answer->next=l1;
}
else{
l1->val=(l1->val+l2->val+carry);
carry=0;
answer->next=l1;
}
answer=answer->next;
l1=l1->next;
l2=l2->next;
}
while(l1!=NULL){
if((l1->val+carry)>=10){
l1->val=(l1->val+carry)-10;
carry=1;
answer->next=l1;
}
else{
l1->val=(l1->val+carry);
carry=0;
answer->next=l1;
}
answer=answer->next;
l1=l1->next;
}
while(l2!=NULL){
if((l2->val+carry)>=10){
l2->val=(l2->val+carry)-10;
carry=1;
answer->next=l2;
}
else{
l2->val=(l2->val+carry);
carry=0;
answer->next=l2;
}
answer=answer->next;
l2=l2->next;
}
if(carry==1){
struct ListNode*newNode=(struct ListNode*)calloc(1,sizeof(struct ListNode));
newNode->val=1;
newNode->next=NULL;
answer->next=newNode;
}
return answerlist.next;
}