1. 程式人生 > 其它 >LeetCode每日一練【2】

LeetCode每日一練【2】

LeetCode每日一練

add_two_numbers

class ListNode {
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }
}
/**
 * @description: 
 * @param {ListNode} l1 連結串列1
 * @param {ListNode} l2 連結串列2
 * @return {ListNode}
 */
const addTwoNumbers = (l1, l2) => {
    let carry = 0   // 計算和的進位
    let current = new ListNode() // 建立一個ListNode連結串列物件
    const listnode = current // 快取ListNode連結串列的頭節點
    while (l1 || l2) {
        if (l1) {
            carry += l1.val
            l1 = l1.next
        }
        if (l2) {
            carry += l2.val
            l2 = l2.next 
        }

        // 儲存值到新建立的連結串列中
        current.next = new ListNode(carry % 10)
        // 切斷當前節點到當前節點的下一個節點
        current = current.next

        // 更新進位,如果大於9,則將進位設定為1,否則設定為0
        carry = carry > 9 ? 1 : 0 
    }

    // 進位溢位,當l1和l2都已經計算完畢後,將溢位的進位放進當前節點的下一個節點中
    if (carry) current.next = new ListNode(carry)

    // 返回根節點後面所有的節點,因為根節點是為初始值,並不是我們所需要的
    return listnode.next
}