在scala中,我需要编写一种方法来查找给定数字中每个数字的乘积。我有以下片段。
def productDigits(number: Int): Int = {
def helper(current: Int, accumulator: Int): Int = {
current match {
case current if current < 10 => accumulator * current
case _ => helper(current / 10, accumulator * (current % 10))
}
}
helper(number, 1)
}
还有更好的方法吗?
这是OP的递归解决方案与Luis的单行代码的jmh基准
@State(Scope.Benchmark)
@BenchmarkMode(Array(Mode.Throughput))
class So59652263 {
def _dexter2305(number: Int): Int = {
def helper(current: Int, accumulator: Int): Int = {
current match {
case current if current < 10 => accumulator * current
case _ => helper(current / 10, accumulator * (current % 10))
}
}
helper(number, 1)
}
def _luis(number: Int): Int = number.toString.map(_.asDigit).product
val num: Int = (math.random * 100000000).toInt
@Benchmark def dexter2305: Int = _dexter2305(num)
@Benchmark def luis: Int = _luis(num)
}
输出
[info] So59652263.dexter2305 thrpt 20 89093066.408 ± 1825286.801 ops/s
[info] So59652263.luis thrpt 20 11585098.230 ± 272966.526 ops/s
我们看到的递归解决方案的吞吐量似乎比单行代码高7倍。