Tuesday, August 18, 2015

Leetcode - Add Two Numbers

Problem

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

What I learnt here? When you're creating a linkedlist, always remember to keep a copy of the start of the linkedlist and the a copy of the previous if necessary. Though this is obvious, its easy to forget this when you're doing while board coding or when you're in an interview.

Solution


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    
  public ListNode storeSum(int l1, int l2, ListNode result)
 {
  int sum = l1 + l2 + result.val;
  result.val = sum%10;
  if(sum > 9) result.next = new ListNode(sum/10); 
  else result.next = new ListNode(0);
  return result;
 }

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

  if(l1== null && l2== null) return null;
  if(l1== null) return l2;
  if(l2== null) return l1;

  ListNode sum = new ListNode(0);
  ListNode result = sum;
  ListNode prevRes;
  do {
   
   prevRes = storeSum(l1.val, l2.val, result);
   result = prevRes.next;
   l1 = l1.next;
   l2 = l2.next;
  }while(l1!=null && l2!=null);

  while(l1!=null)
  {
   prevRes = storeSum(l1.val, 0, result);
   result = prevRes.next;
   l1 = l1.next;
  }

  while(l2!=null)
  {
   prevRes = storeSum(l2.val, 0, result);
   result = prevRes.next;
   l2 = l2.next;
  }

  if(result.val == 0) prevRes.next = null;
  return sum;
 }

        //test functions
         static void printNode(ListNode l)
 {
  while(l!=null)
  {
   System.out.print(l.val);
   l = l.next;
  }
  System.out.println();
 }

 public static void main(String[] args) {

  ListNode l1 = new ListNode(2); 
  l1.next = new ListNode(4); 
  l1.next.next = new ListNode(3);
  Solution.printNode(l1);
  
  ListNode l2 = new ListNode(5); 
  l2.next = new ListNode(6); 
//  l2.next.next = new ListNode(4);
  AddTwoLists.printNode(l2);
  
  Solution ob = new Solution();
  ListNode res = ob.addTwoNumbers(l1, l2);
  Solution.printNode(res);
 }
}

No comments:

Post a Comment