My java solution


  • 0
    D
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(-1);
            ListNode listNode = head;
            boolean carry = false;
            while (l1 != null || l2 != null) {
                int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + (carry ? 1 : 0);
                listNode.next = new ListNode(sum % 10);
                carry = sum >= 10 ? true : false;
    
                listNode = listNode.next;
                l1 = l1 == null ? null : l1.next;
                l2 = l2 == null ? null : l2.next;
            }
    
            if (carry) {
                listNode.next = new ListNode(1);
            }
    
            return head.next;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.