LeetCode # 2 -Add Two Numbers

My submission for LeetCode Add Two Numbers problem:


public class Solution {
   public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      ListNode retVal = new ListNode(0);
      ListNode head = retVal;
      int carry = 0;
      while(l1 != null || l2 != null){
         int temp = carry;
         if(l1 == null){
            temp += l2.val;
            l2 = l2.next;
         } else if (l2 == null){
            temp += l1.val;
            l1 = l1.next;
         } else {
            temp += l1.val + l2.val;
            l1 = l1.next;
            l2 = l2.next;
         } 

         if(temp >= 9){
            carry = 1;
            temp = temp - 10;
         } else {
            carry = 0;
         }

         retVal.val = temp;
         if(l1 != null || l2 != null){
            retVal.next = new ListNode(0);
            retVal = retVal.next;
         } else if(carry == 1){
            retVal.next = new ListNode(1);
            retVal = retVal.next;
         }
      }
   return head;
   }
}

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