Sunday, December 22, 2013

Leetcode: 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

Solution:

This problem's solution is straightforward, only having to be careful to check that you have not arrived to an end of a list. We reuse the nodes to create the solution in order to use constant space.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        int carryOn = (l1.val + l2.val)/10;
        int sum;
        l1.val = (l1.val + l2.val)%10;
        ListNode temp = l1;
        while(temp.next != null && l2.next != null)
        {
            sum = carryOn;
            sum += temp.next.val;
            sum +=  l2.next.val;
            temp.next.val = sum % 10;
            carryOn = sum / 10;
            temp = temp.next;
            l2 = l2.next;
        }
        if(temp.next==null)
            temp.next = l2.next;
        while(temp.next != null)
        {
            sum = carryOn;
            sum += temp.next.val; 
            temp.next.val = sum % 10;
            carryOn = sum / 10;
            temp = temp.next;
        }
        if (carryOn != 0)
            temp.next = new ListNode(carryOn);
        return l1;
    }
}

No comments :

Post a Comment