Add two numbers represented by linked lists in C#

Given two numbers represented by two lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers.

Example 1

Input:
First List: 5->6->3  // represents number 365
Second List: 8->4->2 //  represents number 248
Output
Resultant list: 3->1->6  // represents number 613

Example 2

Input:
First List: 7->5->9->4->6  // represents number 64957
Second List: 8->4 //  represents number 48
Output
Resultant list: 5->0->0->5->6  // represents number 65005

 

class Add_Two_Numbers_Represented_By_Linked_Lists
{
static void Main(string[] args)
{
LinkedList ll1 = new LinkedList();
ll1.AddLast(7);
ll1.AddLast(5);
ll1.AddLast(9);
ll1.AddLast(4);
ll1.AddLast(6);
LinkedList ll2 = new LinkedList();
ll2.AddLast(8);
ll2.AddLast(4);
LinkedList ll3 = new LinkedList();

int maxCount = ll1.Count() > ll2.Count() ? ll1.Count() : ll2.Count();
int carry = 0, temp = 0;
for (int i = 0; i < maxCount; ++i)
{
temp = ll1.ElementAtOrDefault(i) + ll2.ElementAtOrDefault(i);
ll3.AddFirst((temp + carry) % 10);
carry = (temp + carry) / 10;
}

foreach (int item in ll3)
{
Console.Write(item);
}
Console.ReadKey();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s