Leetcode 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.

解法1

主要思路是从两个链表头逐个相加,多余的位用变量carry表示,用来与下一位的两个数相加。
(tips:相加时注意null的处理)

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let carry : number = 0
    let dummy : ListNode = new ListNode(-1, null)
    let head : ListNode = dummy
    
    while(l1 != null || l2 != null || carry != 0){
        let num1 : number = l1 ? l1.val : 0
        let num2 : number = l2 ? l2.val : 0
        let sum : number = num1 + num2 + carry
        carry = Math.floor(sum / 10)
        head.next = new ListNode(sum % 10)
        head = head.next
        l1 ? l1 = l1.next : null
        l2 ? l2 = l2.next : null
    }
    return dummy.next
};

Author: Maple
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Maple !
  TOC