167.Add Two Numbers

1.Description(Easy)

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored inreverseorder, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given7->1->6 + 5->9->2. That is,617 + 295.

Return2->1->9. That is912.

Given3->1->5and5->9->2, return8->0->8.

2.Code

We iterate over the linked list nodes in both lists, adding each digit together and keeping track of the

carry. If we have a carry at the end, we must make sure to add an extra node ad the end of the list

representing the carry digit

    if(l1==null && l2==null){
            return null;
        }

        ListNode dummy=new ListNode(0);
        ListNode current=dummy;
        int carry=0; //控制进位
        while(l1!=null && l2!=null){
            int sum=l1.val+l2.val+carry;//注意每次都要加上carry
            carry=sum/10;
            current.next=new ListNode(sum);

            l1=l1.next;
            l2=l2.next;
            current=current.next;
        }

        while(l1!=null){
            int sum=l1.val+carry;
            carry=sum/10;
            current.next=new ListNode(sum);

            l1=l1.next;
            current=current.next;
        }

        while(l2!=null){
            int sum=l2.val+carry;
            carry=carry/10;
            current.next=new ListNode(sum);

            l2=l2.next;
            current=current.next;
        }

        //最后判断下是否还有进位
        if(carry!=0){
            current.next=new ListNode(carry);
        }
        return dummy.next;
    }

Last updated