Software Engineering
Mid
programming
LeetCode #2 - Add Two Numbers
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 it as a linked list.
Input/Output
Input:(2 -> 4 -> 3) + (5 -> 6 -> 4)
Output:(7 -> 0 -> 8)
Constraints
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9.
- It is guaranteed that the list represents a valid number.
```
class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, current = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
current.next = new ListNode(carry);
}
return dummyHead.next;
}
```
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals
50+ Company Question Banks
5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.
Get Started Free
More Software Engineering Interview Prep
LeetCode #102 - Binary Tree Level Order Traversal: Given a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). Example Input: root = [3,9,20,null,null,15,7] Example Output: [[3],[9,20],[15,7]] Constraints: The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000.
Software Engineering · Mid-level
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.