LeetCode02 两数相加

02

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode resultList = new ListNode();
    ListNode current = resultList;

    ListNode p1 = l1;
    ListNode p2 = l2;
    boolean carry = false;

    while (p1 != null && p2 != null) {
        int sumVal = p1.val + p2.val;
        //分 有进位和无进位 的情况考虑
        if (carry) {
            sumVal = sumVal + 1;
        }
        if (sumVal >= 10) {
            carry = true;
        } else {
            carry = false;
        }
        //这里先移动current再赋值,这样的话头结点就是空的
        current.next = new ListNode();
        current = current.next;

        current.val = sumVal % 10;
        p1 = p1.next;
        p2 = p2.next;
    }
    while (p1 != null) {
        int sumVal = p1.val;
        if (carry) {
            sumVal = sumVal + 1;
        }
        if (sumVal >= 10) {
            carry = true;
        } else {
            carry = false;
        }
        current.next = new ListNode();
        current = current.next;

        current.val = sumVal % 10;
        p1 = p1.next;
    }
    while (p2 != null) {
        int sumVal = p2.val;
        if (carry) {
            sumVal = sumVal + 1;
        }
        if (sumVal >= 10) {
            carry = true;
        } else {
            carry = false;
        }
        current.next = new ListNode();
        current = current.next;

        current.val = sumVal % 10;
        p2 = p2.next;
    }
    if (carry) {
        current.next = new ListNode();
        current = current.next;

        current.val = 1;
    }
    return resultList.next;
}

利用三元运算符?:,并且null补0,让代码更简洁可读

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;

        while (l1 != null || l2 != null) {
            int v1 = l1 == null ? 0 : l1.val;
            int v2 = l2 == null ? 0 : l2.val;
            int sum = v1 + v2 + carry;

            carry = sum / 10;
            int nextVal = sum % 10;
            cur.next = new ListNode(nextVal);
            cur = cur.next;

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }
        return pre.next;
    }
posted @ 2022-09-27 16:20  jrjewljs  阅读(33)  评论(0编辑  收藏  举报