2. Add Two Numbers
Tags:
Medium
Skills:
Linked List
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu cộng hai số nguyên lớn được biểu diễn dưới dạng Linked List, mỗi node chứa một chữ số, các chữ số lưu theo thứ tự ngược lại (chữ số hàng đơn vị nằm ở node đầu tiên). Kết quả cũng cần trả về dưới dạng linked list theo quy tắc tương tự
Approach
Time and space complexity
Solution
1/**
2 * Definition for singly-linked list.
3 * class ListNode {
4 * val: number
5 * next: ListNode | null
6 * constructor(val?: number, next?: ListNode | null) {
7 * this.val = (val===undefined ? 0 : val)
8 * this.next = (next===undefined ? null : next)
9 * }
10 * }
11 */
12
13function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
14 let dummy = new ListNode(0);
15 let curr = dummy;
16 let carry = 0
17 while (l1 !== null || l2 !== null || carry !== 0) {
18 const val1 = l1 ? l1.val : 0;
19 const val2 = l2 ? l2.val : 0;
20 const sum = val1 + val2 + carry;
21 carry = Math.floor(sum / 10);
22 curr.next = new ListNode(sum % 10);
23 curr = curr.next;
24 if (l1) l1 = l1.next;
25 if (l2) l2 = l2.next;
26 }
27 return dummy.next;
28};