Suppose we have a list of digits of a number and we need to compute the number using it i.e. we need to create a single Int
from List<Int>
. Example : [3, 4, 2, 1] → 3421
This is a perfect usecase for reduce operation. Algorithm :
- Initially, the
acc
will be0
. So, we usereduce()
instead offold()
- On each iteration, we compute the accumulated value as
acc * 10 + i
- The final
acc
will be our required number
fun main() {
val digits = listOf(3, 4, 2, 1)
val num = digits.reduce { acc, i ->
acc * 10 + i
}
println(num) // Prints 3421
}