美文网首页
LeetCode题解|2.两数相加 - Javascript

LeetCode题解|2.两数相加 - Javascript

作者: 敦敦实实 | 来源:发表于2022-09-11 15:30 被阅读0次
    function ListNode(val, next) {
      this.val = val === undefined ? 0 : val;
      this.next = next === undefined ? null : next;
    }
    function addTwoNumbers(link1, link2) {
      let l1 = link1;
      let l2 = link2;
      let result = null;
      let currentNext = null;
      let carry = 0;
    
      while (l1 || l2 || carry) {
        let sum = (l1?.val || 0) + (l2?.val || 0) + carry;
        carry = 0;
        if (sum >= 10) {
          carry = 1;
          sum = sum % 10;
        }
        const val = new ListNode(sum, null);
        if (result) {
          currentNext.next = val;
        } else {
          result = val;
        }
        currentNext = val;
    
        l1 = l1?.next;
        l2 = l2?.next;
      }
      return result;
    }
    addTwoNumbers(
      {
        val: 2,
        next: {
          val: 4,
          next: { val: 3, next: null },
        },
      },
      {
        val: 5,
        next: {
          val: 6,
          next: { val: 4, next: null },
        },
      }
    );
    addTwoNumbers(
      {
        val: 0,
        next: null,
      },
      {
        val: 0,
        next: null,
      }
    );
    
    addTwoNumbers(
      {
        val: 9,
        next: {
          val: 9,
          next: {
            val: 9,
            next: {
              val: 9,
              next: {
                val: 9,
                next: {
                  val: 9,
                  next: {
                    val: 9,
                    next: null,
                  },
                },
              },
            },
          },
        },
      },
      {
        val: 9,
        next: {
          val: 9,
          next: {
            val: 9,
            next: {
              val: 9,
              next: null,
            },
          },
        },
      }
    );
    
    

    本文由一文多发运营工具平台 EaseWriting 发布

    相关文章

      网友评论

          本文标题:LeetCode题解|2.两数相加 - Javascript

          本文链接:https://www.haomeiwen.com/subject/rgtfortx.html