Wednesday, January 29, 2014

Code Exercises Round II: #5 in 8 days

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

/**
 * 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 rval = null;
        ListNode current = null;
        
        int carry = 0;

        while(l1 != null || l2 != null) {
            int subtotal = 0;
            
            if(l1 != null && l2 != null) {
                subtotal = l1.val + l2.val + carry;
                l1 = l1.next;
                l2 = l2.next;
            }
            // only l2 has content
            else if (l1 == null) {
                subtotal = l2.val + carry;
                l2 = l2.next;
            }
            // only l1 has content
            else {
                subtotal = l1.val + carry;
                l1 = l1.next;
            }
            
            if(subtotal > 9) {
                carry = 1;
            }                   
            else {
                carry = 0;
            }
            
            ListNode subtotalNode = new ListNode(subtotal % 10);
            
            // initialize
            if(rval == null) {
                current = subtotalNode;
                rval = current;
            }
            else {
                current.next = subtotalNode;
                current = current.next;
            }
        }
        
        if(carry > 0) {
            current.next = new ListNode(1);
        }
        return rval;
    }
}

No comments:

Post a Comment