Skip to content

Commit cd5e169

Browse files
committed
Add solution for 2. Add Two Numbers
1 parent f4aa404 commit cd5e169

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ The repository contains the best versions of my solutions to [LeetCode](https://
99
| # | Title | Solution | Time | Space |
1010
|---| ----- | -------- | ---- | ----- |
1111
|1814|[Count Nice Pairs in an Array](https://leetcode.com/problems/contains-duplicate/)|[TypeScript](./Solutions/TypeScript/1814-count-nice-pairs-in-an-array.ts)|O(n)|O(n)|
12+
|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)|[TypeScript](./Solutions/TypeScript/2-add-two-numbers.ts)|O(n)|O(n)|
1213

1314
## Solutions Python
1415

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
3+
4+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
5+
6+
Example 1:
7+
Input: l1 = [2,4,3], l2 = [5,6,4]
8+
Output: [7,0,8]
9+
Explanation: 342 + 465 = 807.
10+
11+
Example 2:
12+
Input: l1 = [0], l2 = [0]
13+
Output: [0]
14+
Example 3:
15+
16+
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
17+
Output: [8,9,9,9,0,0,0,1]
18+
19+
Constraints:
20+
21+
The number of nodes in each linked list is in the range [1, 100].
22+
0 <= Node.val <= 9
23+
It is guaranteed that the list represents a number that does not have leading zeros.
24+
*/
25+
26+
class ListNode {
27+
val: number;
28+
next: ListNode | null;
29+
constructor(val?: number, next?: ListNode | null) {
30+
this.val = val === undefined ? 0 : val;
31+
this.next = next === undefined ? null : next;
32+
}
33+
}
34+
35+
function addTwoNumbers(
36+
l1: ListNode | null,
37+
l2: ListNode | null
38+
): ListNode | null {
39+
let current = new ListNode(0);
40+
let result = current;
41+
42+
let carry = 0;
43+
44+
while (l1 || l2 || carry) {
45+
let value1 = l1 ? l1.val : 0;
46+
let value2 = l2 ? l2.val : 0;
47+
48+
let sum = value1 + value2 + carry;
49+
50+
carry = 0;
51+
52+
if (sum > 9) {
53+
carry = ~~(sum / 10);
54+
sum = sum % 10;
55+
}
56+
57+
current.next = new ListNode(sum);
58+
current = current.next;
59+
60+
if (l1) l1 = l1.next;
61+
if (l2) l2 = l2.next;
62+
}
63+
64+
return result.next;
65+
}

0 commit comments

Comments
 (0)