Friday, July 3, 2015

#codingexercise
/***
Add 2 numbers represented as linked list and return the resulting sum as a linked list.

How are numbers represented as linked list?
Suppose we have 459, it is represented as:
4->5->9->null
So 4 is the head and 9 is the tail.

Say we are given 2 numbers like: 459 and 891, their sum is 1350. That will be represented as:
1->3->5->0.

Implement the function that takes head pointer of 2 numbers as linked list and
returns a head pointer to a new linked list, which is basically the sum of both the numbers.
***/

Node GetSum(Node root1, Node root2)
{

// read the value from root 1
int val1 = GetValue(root1);
// read the value from root 2
int val2 = GetValue(root2);
// write the value of root1 + root2
if ( val1 + val2 < val1 || val1 + val2 < val2) // overflow
   return NULL; // or raise exception
return WriteValue(val1 + val2);
}

Node WriteValue(int val)
{
  Node root = NULL;
  int v = val;
  int len = 0;
  while (v != 0 ) {
    len = len + 1;
    v  = v / 10;
  }
  v =  val;
  Node Prev = null;
  for ( i = 0; i < len ; i++)
  {
    var n = new Node();
    n.Data = (Math.floor(v / Power(10, len - i - 1))) % 10;
    n.Next = Null;
    if (Prev) {
        prev.next = n;
        prev = n;
    }
    else
        root = n;
       
  }
  return root;
}

int GetValue(Node root1)
{
Node cur = root1;
int val1 = 0;
int len = 0;
while(cur) 
{
  
   len = len + 1;
   cur = cur.Next;
}

// len = 2
cur = root1;
for ( i = 0; i < len; i++)
{
  val1 += cur.Data * Power(10, len - i - 1);
  cur = cur.Next;
}

// val1 = 29
}


NULL list2
list1 NULL

UnitValue List2
list1 UnitValue

ArbitraryValue List2
List1 ...


Overflow & Underflow

No comments:

Post a Comment