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

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ListNode runner1=l1;
        ListNode runner2=l2;
        ListNode head = new ListNode(-1);
        ListNode runner = head;
        int carry=0;
        while(runner1!=null || runner2!=null ||carry!=0){
            int val1 = runner1==null?0:runner1.val;
            int val2 = runner2==null?0:runner2.val;
            int sum =val1+val2+carry;
            if(sum>9){
                carry=1;
            }else{
                carry=0;
            }
            runner.next = new ListNode(sum%10);
            runner = runner.next;
            runner1 = runner1==null?null:runner1.next;
            runner2 = runner2==null?null:runner2.next;
        }

        return head.next;
    }

 

 

FacebookTwitterGoogle+Share

Leave a Reply

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