leetcode 2 Add Two Numbers

2020-05-28  本文已影响0人  叫我坤坤

题目

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

思路

代码

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 新增空的头结点,最终返回head.next即可
        ListNode head = new ListNode();
        ListNode nowNode = head;

        // 进位值
        int addUp = 0;
        while (l1 != null || l2 != null) {
            int value = addUp;
            if (l1 != null) {
                value += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                value += l2.val;
                l2 = l2.next;
            }
            addUp = value / 10;
            value = value % 10;
            nowNode.next= new ListNode(value);
            nowNode = nowNode.next;
        }
        // 最后进位值大于0,需要新增进位值的节点
        if (addUp > 0) {
            nowNode.next= new ListNode(addUp);
        }
        return head.next;
    }
上一篇下一篇

猜你喜欢

热点阅读