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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //get the first digit of two input numbers
        ListNode d1 = l1;
        ListNode d2 = l2;
        //store the digit sum
        int sum = 0;
        //the return linked list
        ListNode ret = new ListNode(0);
        ListNode itr = ret;
        while (d1 != null || d2 != null) {
            //carry
            sum = sum/10;
            if (d1 != null) {
                sum += d1.val;
                d1 = d1.next;
            }
            if (d2 != null) {
                sum += d2.val;
                d2 = d2.next;
            }
            //add digit to the sum:
            itr.next = new ListNode (sum%10);
            itr = itr.next;
        }
        //special case: check if a carry is needed to be added
        if (sum/10 == 1)
            itr.next = new ListNode(1);

        return ret.next;
    }
}

ref: Leetcode discusson

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