Leetcode

00002. Leetcode: Add Two Numbers – Problem and Solution


Introduction to Add Two Numbers Problem

The “Add Two Numbers” leetcode problem is a classic algorithmic challenge frequently encountered in coding interviews. The problem statement goes like this: Given two non-empty linked lists representing two non-negative integers, where each node in the linked list contains a single digit and the digits are stored in reverse order, add the two numbers and return the sum as a linked list. It’s assumed that the two numbers do not contain any leading zeros, except for the number 0 itself.

Example

Input:

l1 = [2,4,3]
l2 = [5,6,4]

Output:

[7,0,8]

Explanation: 342 + 465 = 807.

Constraints

  • The number of nodes in each linked list is in the range [1, 100].
  • Each node’s value is between 0 and 9.
  • It is guaranteed that the list represents a number that does not have leading zeros.

Solution: Simulating Addition with Linked Lists

Problem Analysis

To solve this problem, we need to simulate the process of adding two numbers. Since the digits are stored in reverse order, we can traverse the linked lists simultaneously, adding corresponding digits along with any carry from the previous step. The result is a new linked list representing the sum of the two numbers.

C# Implementation

Here’s the C# implementation of the solution:

Solution
public class AddTwoNumbersSolution
{
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
    {
        ListNode result = new ListNode();
        ListNode current = result;
        int carry = 0;

        while (l1 != null || l2 != null || carry != 0)
        {
            int sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
            carry = sum / 10;

            current.next = new ListNode(sum % 10);
            current = current.next;

            l1 = l1?.next;
            l2 = l2?.next;
        }

        return result.next;
    }
}

Explanation

  • We create a result linked list to store the sum.
  • We use a current pointer to keep track of the current node in the result linked list.
  • We iterate through both input linked lists (l1 and l2) simultaneously, calculating the sum of corresponding digits along with any carry from the previous step.
  • We update the result linked list with the current digit of the sum and move the pointers to the next nodes in the input linked lists and the result linked list.

Conclusion

The “Add Two Numbers” problem is an excellent exercise in linked list manipulation and simulating mathematical operations. The solution provides an efficient way to add two numbers represented as linked lists, and the approach can be generalized to similar problems involving linked lists.

Danilo Cavalcante

Working with web development since 2005, currently as a senior programmer analyst. Development, maintenance, and integration of systems in C#, ASP.Net, ASP.Net MVC, .Net Core, Web API, WebService, Integrations (SOAP and REST), Object-Oriented Programming, DDD, SQL, Git, and JavaScript

Recent Posts

Collections and LINQ Queries in C#

In modern C# programming, working with data collections is a common task. Understanding how to…

2 days ago

Exception Handling in C#: try-catch, finally, and Custom Exceptions

Exception handling is a critical part of writing robust and maintainable C# applications. It allows…

3 days ago

Do Docker Containers Take Up Space?

One of the common questions among Docker users is whether Docker containers consume disk space.…

6 months ago

How to Use “Order By” in C#

Sorting data is a common operation in programming, allowing you to organize information in a…

6 months ago

How to Split a String into an Array in C#

Splitting a string into an array of substrings is a common operation in C# programming,…

6 months ago

Starting the Docker Daemon: A Step-by-Step Guide

Starting the Docker daemon is the first step towards managing Docker containers and images on…

6 months ago