This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Sunday, 31 May 2015

Add two numbers represented by linked lists. (Numbers are stored in backward fashion.)


package linkedlist.singly;

//Add two numbers represented by linked lists 
// 245   :  5 -> 4 -> 2
// 99789 :  9 -> 8 -> 7 -> 9 -> 9
// Ans   :  100034
public class Add2NumbersInLinkListType1{

 public static void main(String[] args) {
  
  //Number is 245
  Node templ11 = new Node(5);
  Node templ12 = new Node(4);
  Node templ13 = new Node(2);
  
  //Number is 99789
  Node templ21 = new Node(9);
  Node templ22 = new Node(8);
  Node templ23 = new Node(7);
  Node templ24 = new Node(9);
  Node templ25 = new Node(9);
  
  templ11.setNext(templ12);
  templ12.setNext(templ13);
  
  templ21.setNext(templ22);
  templ22.setNext(templ23);
  templ23.setNext(templ24);
  templ24.setNext(templ25);
 
  //100034
  System.out.println(findSum(templ11, templ21));  
 }
 
 private static String findSum(Node l1, Node l2){
  String result="";
  int sum=0;
  int carry=0;
  while(l1!=null || l2!=null){
   sum = (l1==null?0:l1.getData()) + (l2==null?0:l2.getData()) + carry;
   
   if(sum>9){
    carry=1;
   }else{
    carry=0;
   }
   
   sum=sum % 10;
   
   result = sum+result;
   if(l1!=null){
    l1=l1.getNext();
   }
   if(l2!=null){
    l2=l2.getNext();
   }
  }
  
  if(carry==1){
   return 1+result; 
  }else{
   return result;
  } 
 }
}


No comments:

Post a Comment