Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

package tests;

import java.util.LinkedList;

import org.testng.annotations.Test;

class ListNode
{

ListNode()
{

}
int val;
ListNode next;
ListNode(int x)
{
val=x;
}

}
class Solution {

public Solution()
{

}
public LinkedList<Integer> addTwoNumbers(ListNode l1, ListNode l2) {

LinkedList<Integer> solution=new LinkedList<Integer>(); ;
int temp=0;
int value;
int left;
int tenth = 0;
while((l1!=null) && (l2!=null))
{
value=l1.val+l2.val;
temp=value/10;
left=value%10;

if(temp!=0)
{
solution.add(left);
tenth=temp;
}
else
{
solution.add(left+tenth);
}
l1=l1.next;
l2=l2.next;
}
return solution;

}
}
public class SolutionTest {

@Test
public void testNode() {

ListNode l1=new ListNode(2);
ListNode l2=new ListNode(4);
ListNode l3=new ListNode(3);
l1.next=l2;
l2.next=l3;
ListNode l4=new ListNode(5);
ListNode l5=new ListNode(6);
ListNode l6=new ListNode(4);
l4.next=l5;
l5.next=l6;
LinkedList<Integer> solution;
Solution sol=new Solution();
solution=sol.addTwoNumbers(l1, l4);
for(int i:solution)
{
System.out.println(i);
}

}
}

Advertisements

About qainterviews

Software Geek,QA Expert,Blogger
This entry was posted in Uncategorized. Bookmark the permalink.

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