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

/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function

        ListNode head = new ListNode(-1);
        ListNode runner = head;

        int carry = 0;
        while(l1!=null || l2!=null){
            int val1 = l1==null?0:l1.val;
            int val2 = l2==null?0:l2.val;
            int sum = val1 + val2 + carry;
            
            if(sum>9){
                sum = sum - 10;
                carry = 1;
            }else{
                carry = 0;
            }
            if(head.val==-1){
                head.val = sum;
            }else{
                ListNode newNode = new ListNode(sum);
                runner.next = newNode;
                runner = runner.next;
            }
            l1 = l1==null?null:l1.next;
            l2 = l2==null?null:l2.next;
        }
        
        if(carry==1){
            ListNode newNode = new ListNode(1);
            runner.next = newNode;            
        }
        return head;
    }
}

 

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *