Wednesday, January 7, 2015

LeetCode 2: 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;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode helper = new ListNode(0); // Helper node of sum list
        
        ListNode cur = helper; // Current node of sum list
        ListNode cur1 = l1; // Current node of list 1
        ListNode cur2 = l2; // Current node of list 2

        int carry = 0;
        
        while (cur1!=null || cur2!=null)
        {
            if (cur1 != null)
            {
                carry += cur1.val;
                cur1 = cur1.next;
            }
            
            if (cur2 != null)
            {
                carry += cur2.val;
                cur2 = cur2.next;                
            }
            
            cur.next = new ListNode(carry%10);
            cur = cur.next;
            carry = carry/10;
        }
        
        // Note: Don't miss the node.
        if (carry == 1)
            cur.next = new ListNode(1);
        
        return helper.next;
    }
}

No comments:

Post a Comment