My AC Java solution


  • 0
    N
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode head = l1;
        ListNode prev = l1;
        while (l2 != null || carry != 0) {
            if (l1 == null) {
                l1 = new ListNode(0);
                prev.next = l1;
            }
            if (l2 != null) {
                l1.val += (l2.val + carry);
                l2 = l2.next;
            } else {
                l1.val += carry;
            }
            carry = l1.val / 10;
            l1.val %= 10;
            prev = l1;
            l1 = l1.next;
        }
        return head;
    }

Log in to reply
 

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