两数相加

74 阅读1分钟

题目

递归

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

    public ListNode digui(ListNode l1, ListNode l2, int carry) {
        if (l1 == null && l2 == null) {
            if (carry != 0) {
                return new ListNode(carry);
            }
            return null;
        }
        // 如果某个加数位数较短 补充前导0 使得位数补齐
        l1 = l1 == null ? new ListNode(0) : l1;
        l2 = l2 == null ? new ListNode(0) : l2;

        ListNode nextAdd = null;
        if (l1.val + l2.val + carry > 9) {
            nextAdd = digui(l1.next, l2.next, 1);
        } else {
            nextAdd = digui(l1.next, l2.next, 0);
        }
        ListNode nowNode = new ListNode((l1.val + l2.val + carry) % 10);
        nowNode.next = nextAdd;
        return nowNode;

    }

基本思路

  1. 直接从链表的头节点开始相加, 如果有进位就传递进位, 本次递归得到的是当前节点的值, next节点由下个递归的返回得到

  2. 如果两个链表长度不同, 对较短的链表补充val为0的节点用于计算

  3. 当两个节点都为null时, 如果进位还有值, 需要返回一个val为1的节点