bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 2. Add Two Numbers

2. Add Two Numbers

Leetcode Solutions

Elementary Math Approach

  1. Initialize a dummy head node to help simplify the code.
  2. Initialize a variable carry to 0.
  3. Loop through both linked lists (l1 and l2) until you reach the end of both lists and carry is 0.
  4. For each node, sum the values of l1, l2, and carry.
  5. The new digit is the sum modulo 10, and the new carry is the sum divided by 10.
  6. Move to the next nodes in l1 and l2.
  7. If one list is longer, continue the process with the remaining digits.
  8. If there is a carry left after the end of both lists, create a new node with that carry.
  9. Return the next node of the dummy head, which is the start of the result linked list.
UML Thumbnail

Reverse and Add Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...