Leetcode Practice

LC 2. Add Two Numbers

Last updated
Reading time
1 min read

The problem

First Solution

// Definition for singly-linked list.
class ListNode {
  val: number
  next: ListNode | null
  constructor(val?: number, next?: ListNode | null) {
    this.val = val === undefined ? 0 : val
    this.next = next === undefined ? null : next
  }
}

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
  let carry = 0
  let current = new ListNode()
  let answer = current
  while (l1 || l2 || carry) {
    let digit1 = 0
    let digit2 = 0
    if (l1) {
      digit1 = l1.val
      l1 = l1.next
    }
    if (l2) {
      digit2 = l2.val
      l2 = l2.next
    }
    const sum = digit1 + digit2 + carry
    const answerDigit = sum % 10
    carry = sum > 9 ? 1 : 0
    const newNode = new ListNode(answerDigit)
    current.next = newNode
    current = newNode
  }

  return answer.next
}