40. 求两个单链表之和

RT

打卡Scala集合库版

  // Time: O(max(m, n)), Space: O(max(m, n))
  def twoListNumbersSum(list1: Iterable[Int], list2: Iterable[Int]): Seq[Int] = {
    var carry = 0 // 进位
    var result = List[Int]()
    val l1 = list1.iterator
    val l2 = list2.iterator
    while (l1.hasNext || l2.hasNext || carry != 0) {
      var sum = carry
      if (l1.hasNext) sum += l1.next()
      if (l2.hasNext) sum += l2.next()
      carry = sum / 10
      result ::= sum % 10
    }
    result.reverse
  }

  // scalatest
  twoListNumbersSum(List(1, 2, 3), Vector(6, 7, 8, 9)) should be(Array(7, 9, 1, 0, 1))
}