Sunday, June 14, 2015

Add Two Numbers | Leetcode

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: Maintain a carry number (1 or 0). Go through each number in L1 and L2 until both get exhausted, and also until the carry number is zero. Add each digit in L1 and L2 and then return the new linked list as the answer.
/**
 * 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) {
        ListNode head = null;
        ListNode cur = null;
        int carry = 0;
        
        while ((l1 != null) || (l2 != null) || (carry > 0)) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            if (sum >= 10) {
                carry = 1;
                sum -= 10;
            } else {
                carry = 0;
            }
            if (head == null) {
                cur = head = new ListNode(sum);
            } else {
                cur = cur.next = new ListNode(sum);
            }
        }
        
        return head;
    }
}

No comments: