File tree Expand file tree Collapse file tree 2 files changed +66
-1
lines changed Expand file tree Collapse file tree 2 files changed +66
-1
lines changed Original file line number Diff line number Diff line change @@ -25,5 +25,5 @@ A repository to store leetcode solved problems.
25
25
26
26
| Number | Title | Tags | Status | Solution |
27
27
| --------| ----------------------| -----------------------------------------------------------------------------------------| ----------------| ------------------------------------------------------------------------------------------------------------|
28
- | 36 | Valid Sudoku | ` Array ` ` Hash Table ` ` Matrix ` | :construction : | [ File] ( https://github.com/johnazedo/interview-questions/blob/main/leetcode/medium/valid_sudoku.go ) |
28
+ | 02 | Add Two Numbers | ` Linked List ` ` Math ` ` Recursion ` | :construction : | [ File] ( https://github.com/johnazedo/interview-questions/blob/main/leetcode/medium/add_two_numbers.cpp ) |
29
29
Original file line number Diff line number Diff line change
1
+ #include " ../data_structures.h"
2
+ #include < bits/stdc++.h>
3
+
4
+ using namespace std ;
5
+
6
+ /*
7
+ * Number: 02
8
+ * Difficult: Medium
9
+ * Link: https://leetcode.com/problems/add-two-numbers/
10
+ * Tags: Linked List, Math, Recursion
11
+ */
12
+
13
+ class AddTwoNumbers {
14
+ public:
15
+ /*
16
+ * Time complexity: O(N)
17
+ * Space complexity: O(N)
18
+ *
19
+ * Time beats: 84.96%
20
+ * Space beats: 95.5%
21
+ */
22
+ ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) {
23
+ return helper (l1, l2);
24
+ }
25
+
26
+ ListNode* helper (ListNode* l1, ListNode* l2, int has_one = 0 ) {
27
+ int sum, number, up;
28
+
29
+ if (l1 == NULL && l2 == NULL && has_one == 0 ) {
30
+ return NULL ;
31
+ }
32
+
33
+ if (l1 == NULL && l2 == NULL && has_one != 0 ) {
34
+ l1 = new ListNode (has_one, NULL );
35
+ return l1;
36
+ }
37
+
38
+ if (l1 == NULL ) {
39
+ sum = l2->val + has_one;
40
+ l1 = new ListNode (0 , NULL );
41
+ }
42
+
43
+ if (l2 == NULL ) {
44
+ sum = l1->val + has_one;
45
+ l2 = new ListNode (0 , NULL );
46
+ }
47
+
48
+ if (l1 != NULL && l2 != NULL ) {
49
+ sum = l1->val + l2->val + has_one;
50
+ }
51
+
52
+ if (sum >= 10 ) {
53
+ number = sum % 10 ;
54
+ up = 1 ;
55
+ } else {
56
+ number = sum;
57
+ up = 0 ;
58
+ }
59
+
60
+ l1->val = number;
61
+ l1->next = helper (l1->next , l2->next , up);
62
+
63
+ return l1;
64
+ }
65
+ };
You can’t perform that action at this time.
0 commit comments