All files / leetCode 0002.ts

100% Statements 24/24
100% Branches 16/16
100% Functions 1/1
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45            7x 1x   6x 1x   5x 1x   4x 4x 4x 4x 4x   4x   18x 15x 15x     18x 15x 15x     18x 18x 18x       4x 4x   4x    
import { ListNode } from './List'
 
export default function addTwoNumbers(
  l1: ListNode<number> | null,
  l2: ListNode<number> | null,
): ListNode<number> | null {
  if (l1 === null && l2 === null)
    return null
 
  if (l1 === null)
    return l2
 
  if (l2 === null)
    return l1
 
  let c1: ListNode<number> | null = l1
  let c2: ListNode<number> | null = l2
  const head = new ListNode(0)
  let tail = head
  let sum = 0
 
  while (c1 !== null || c2 !== null) {
    // traverse longer list
    if (c1 !== null) {
      sum += c1.val
      c1 = c1.next
    }
 
    if (c2 !== null) {
      sum += c2.val
      c2 = c2.next
    }
 
    tail.next = new ListNode(sum % 10)
    sum = Math.floor(sum / 10)
    tail = tail.next
  }
 
  // Note that can have carry at the last digit
  if (sum === 1)
    tail.next = new ListNode(1)
 
  return head.next
}