2.Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

代码实现

 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return getNext(l1,l2,0);
    }

    private ListNode getNext(ListNode l1,ListNode l2,int count) {
        if(l1==null) l1 = new ListNode(0);
        if(l2==null) l2 = new ListNode(0);
        int newVal = (l1.val + l2.val + count)%10;
        int newCount = (l1.val + l2.val + count)/10;
        ListNode next = new ListNode(newVal);
        if((l1!=null && l1.next != null) || (l2!=null && l2.next != null) || newCount>0) {
            next.next = getNext(l1.next,l2.next,newCount);
        }
        return next;
    }

分析

主要有一个进位要考虑,还有就是一个递归调用,递归调用的出口是l1和l2和next都是null和进位是0

你可能感兴趣的:(2.Add Two Numbers)