Share my JAVA solution


  • 1
    P
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode ret = new ListNode(0);
            ListNode cur = ret;
            int carry = 0;
            for(; l1 != null && l2 != null; cur = cur.next, l1 = l1.next, l2 = l2.next) {
                int sum = l1.val + l2.val + carry;
                cur.next = new ListNode(sum > 9 ? sum - 10 : sum);
                carry = sum > 9 ? 1 : 0;
            }
            
            if(l1 != null || l2 != null) {
                if(l2 != null)
                    l1 = l2;
                cur.next = l1;
                while(l1 != null && carry != 0) {
                    if(l1.val + carry > 9) {
                        l1.val = l1.val + carry - 10;
                        carry = 1;
                        l1 = l1.next;
                    } else {
                        l1.val = l1.val + carry;
                        carry = 0;
                    }
                }
                if(l1 == null) {
                    while(cur.next != null)
                        cur = cur.next;
                    cur.next = new ListNode(1);
                }
            } else if(carry != 0) {
                cur.next = new ListNode(1);
            }
           
            return ret.next;
        }

Log in to reply
 

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