scala - 加一链表: Functional Approach

标签 scala functional-programming

我一直在为这个 leetcode 问题绞尽脑汁。想知道是否有一种实用的方法可以解决这个问题。我能想到的就是使用可变对象(在 Scala 中)。

给定一个表示为数字链接列表的非负整数,该整数加一。

存储数字时,最高有效数字位于列表的开头。

示例1:

输入:head = [1,2,3] 输出:[1,2,4]

示例2:

输入:head = [0] 输出:[1]

限制:

链表中的节点数量在[1, 100]范围内。

0 <= Node.val <= 9

链表表示的数字除了零本身之外不包含前导零。

 * Definition for singly-linked list.
 * class ListNode(_x: Int = 0, _next: ListNode = null) {
 *   var next: ListNode = _next
 *   var x: Int = _x
 * }
 */
object Solution {
    def plusOne(head: ListNode): ListNode = {
        
    }
}

更有趣的输入/输出 = [1,9,9,9,9] => [2,0,0,0,0]

最佳答案

(tail)递归来救援!

type Digit = Int // Refined [1..9]
type Number = List[Digit]

def plusOne(number: Number): Number = {
  def sumDigits(d1: Digit, d2: Digit): (Digit, Digit) = {
    val r = d1 + d2
    (r % 10) -> (r / 10)
  }
  
  @annotation.tailrec
  def loop(remaining: Number, remainder: Digit, acc: Number): Number =
    remaining match {
      case digit :: digits =>
        val (result, newRemainder) = sumDigits(digit, remainder)
        loop(remaining = digits, newRemainder, result :: acc)
      
      case Nil =>
        if (remainder != 0) remainder :: acc
        else acc
    }
    
  loop(remaining = number.reverse, remainder = 1, acc = List.empty)
}

你可以这样使用:

plusOne(List(1, 2, 3))
// res: Number = List(1, 2, 4)

您可以看到代码正在运行 here .

关于scala - 加一链表: Functional Approach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65363564/

相关文章:

scala - Scala 中的 protected 函数

algorithm - 功能性 "All except one"

python - 应用三参数函数的 'reduce' 列表的 Pythonic 方法是什么?

c# - 在 C# 中使用 Language-Ext 返回 Either 的链式异步操作

scala - Play Framework 从 Play 服务器向 "somesite.com"发出 http 请求并将响应发送回浏览器

scala - Clojure 相当于 Scalaz Foldable 的折叠图是什么?

Scala IntelliJ 警告 "dynamic invocation could be replaced with a constructor invocation"

javascript - 在这种情况下,函数式编程的效率是否较低?

python - 如何按键进行迭代器的完整外连接/合并?

scala - 在连续 block 中读取非常大的文件 (~ 1 TB)