Bernard Wong
  • Software Engineer
  • Problems
    • Lowest Common Ancestor of a Binary Tree
    • Longest Substring Without Repeating Characters
    • Longest Palindromic Substring
    • Longest Common Prefix
    • Isomorphic Strings
    • Integer to Roman
    • Frog Jump
    • Find the Difference
    • Find k closest elements to a given value
    • Longest Common Subsequence
    • Binary Search Tree from Sorted Array
    • Balanced Binary Tree
    • Sort Using Two Stacks
    • O(1) Stack
    • k-th element to last of a LinkedList
    • Dedup LinkedList
    • Check Rotated String
    • Compress String by Character Count
    • Escape HTML whitespace
    • Check String Permutation
    • Unique String
    • Container With Most Water
    • 4 Sum
    • 3 Sum Closest
    • 3 Sum
    • 2 Sum
    • Maximum Subarray
    • Nested List Weight Sum
    • Palindrome Number
    • Pow(x, n)
    • Regular Expression Matching
    • Remove Nth Node From End of List
    • Reverse Integer
    • Roman to Integer
    • Rotate Array
    • Search a 2D Matrix
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Valid Parentheses
    • ZigZag Conversion
    • Quicksort
    • Add Two Numbers
    • Best Time to Buy and Sell Stock
    • Letter Combinations of a Phone Number
  • Data Structures
    • Heap
Powered by GitBook
On this page
  1. Problems

Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
class ListNode(var value: Int, var next: ListNode = null) {
  def +(that: ListNode): ListNode = {
    if (that == null) this
    else {
      val sum = this.value + that.value
      var next = new ListNode(sum / 10) + this.next + that.next
      if (next.value == 0 && next.next == null) next = null
      new ListNode(sum % 10, next)
    }
  }
}

/**
  * wrapper function
  * @param l1
  * @param l2
  * @return
  */
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
  if (l1 != null && l2 != null) l1 + l2
  else if (l1 == null) l2
  else l1
}

/**
  * utility function
  * @param nums
  * @return
  */
def createLinkedList(nums: Array[Int]): ListNode = {
  nums
    .map(num => new ListNode(num))
    .foldRight[ListNode](null)((l: ListNode, r: ListNode) => {
    l.next = r; l
  })
}

/**
  * utility function
  * @param n
  */
def printLinkedList(n: ListNode): Unit = {
  var head = n
  while (head != null) {
    println(head.value)
    head = head.next
  }
}

var n1 = createLinkedList(Array(0))
var n2 = createLinkedList(Array(1))

printLinkedList(addTwoNumbers(n1, n2))

PreviousQuicksortNextBest Time to Buy and Sell Stock

Last updated 6 years ago