forked from Aadi71/Data-Structures-and-Algorithms-with-Aadi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-two-numbers.cpp
53 lines (50 loc) · 1.62 KB
/
add-two-numbers.cpp
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
// https://leetcode.com/problems/add-two-numbers/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* main = new ListNode(0);
ListNode* ret = main;
int carry = 0;
int sum;
while(l1 || l2 || carry){
sum = (l1 != NULL ? l1 -> val : 0) + (l2 != NULL ? l2 -> val : 0) + carry;
carry = sum / 10;
main -> next = new ListNode(sum % 10);
l1 = l1 != NULL ? l1 -> next : l1;
l2 = l2 != NULL ? l2 -> next : l2;
main = main -> next;
}
// while(l1 != NULL && l2 != NULL){
// sum = carry + l1 -> val + l2 -> val;
// carry = sum / 10;
// sum = sum % 10;
// main -> next = new ListNode(sum);
// main = main -> next;
// l1 = l1 -> next;
// l2 = l2 -> next;
// }
// while(l1){
// sum = carry + l1 -> val;
// carry = sum / 10;
// sum = sum % 10;
// main -> next = new ListNode(sum);
// main = main -> next;
// l1 = l1 -> next;
// }
// while(l2){
// sum = carry + l2 -> val;
// carry = sum / 10;
// sum = sum % 10;
// main -> next = new ListNode(sum);
// main = main -> next;
// l2 = l2 -> next;
// }
// while(carry > 0){
// sum = carry % 10;
// main -> next = new ListNode(sum);
// main = main -> next;
// carry /= 10;
// }
return ret -> next;
}
};