孙晓聪
  • 最新
  • 博客
  • 书评
  • Add Two Numbers

    Description

    original description

    Solutions

    Clear Version

    simulate the calculation

    function ListNode(val, next) {
      this.val = val === undefined ? 0 : val;
      this.next = next === undefined ? null : next;
    }
    
    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var addTwoNumbers = function (l1, l2) {
      const head = new ListNode();
      let current = head;
      let carry = 0;
    
      while (l1 && l2) {
        const sum = l1.val + l2.val + carry;
        const val = sum % 10;
        carry = Math.floor(sum / 10);
    
        current.next = new ListNode(val);
        current = current.next;
        l1 = l1.next;
        l2 = l2.next;
      }
    
      while (l1) {
        const sum = l1.val + carry;
        const val = sum % 10;
        carry = Math.floor(sum / 10);
    
        current.next = new ListNode(val);
        current = current.next;
        l1 = l1.next;
      }
    
      while (l2) {
        const sum = l2.val + carry;
        const val = sum % 10;
        carry = Math.floor(sum / 10);
    
        current.next = new ListNode(val);
        current = current.next;
        l2 = l2.next;
      }
    
      if (carry) {
        current.next = new ListNode(carry);
      }
    
      return head.next;
    };
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)

    Merge Calculation

    function ListNode(val, next) {
      this.val = val === undefined ? 0 : val;
      this.next = next === undefined ? null : next;
    }
    
    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var addTwoNumbers = function (l1, l2) {
      const head = new ListNode();
      let current = head;
      let carry = 0;
    
      while (l1 || l2) {
        const sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;    // the new syntax
        const val = sum % 10;
        carry = Math.floor(sum / 10);
    
        current.next = new ListNode(val);
        current = current.next;
        l1 = l1?.next;
        l2 = l2?.next;
      }
    
      if (carry) {
        current.next = new ListNode(carry);
      }
    
      return head.next;
    };
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)