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 contains a single digit. Add the two numbers and return the sum as a linked list.

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

 

Example:

    Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
    Output: [8,9,9,9,0,0,0,1]

 

 方法一:

由于链表是逆向存储,所以可以从第一位开始对应相加,carry是进位,sum = (n1+n2+carry)%10,  carry = n1+n2+carry/10. 相加到两个链表都结束.最后看carry是否大于0.

为方便,可以new 一个head节点。

static class ListNode{
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
public  ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode dumpy = new ListNode(-1);
        ListNode cur = dumpy;
        int carry = 0;
        while(l1 != null || l2!= null){
            int d1 = l1 == null ? 0 : l1.val;
            int d2 = l2 == null ? 0 : l2.val;
            int sum = d1 + d2 + carry;
            carry = sum >= 10 ? 1: 0;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            if(l1 != null) l1 = l1.next;
            if(l2 != null ) l2 = l2.next;
        }
        if(carry == 1) cur.next = new ListNode(1);
        return dumpy.next;
    }

 

时间复杂度O(max(m,n))

方法二:

可以用递归

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

    ListNode addTwoNumbers(ListNode l, ListNode r, int i) {
        if (l == null && r == null && i == 0) return null;
        int sum = (l != null ? l.val : 0) + (r != null ? r.val : 0) + i;
        var node = new ListNode(sum % 10);
        node.next = addTwoNumbers(l != null ? l.next : null, r != null ? r.next : null, sum / 10);
        return node;
    }

 

 

参考链接:

https://leetcode.com/problems/add-two-numbers/

https://leetcode-cn.com/problems/add-two-numbers/


 

posted @ 2020-11-07 18:31  diameter  阅读(150)  评论(0编辑  收藏  举报