Kotlin:Lambda,范围,地图,过滤器和缩小/折叠 [英] Kotlin: Lambdas, range, map, filter and reduce/fold
本文介绍了Kotlin:Lambda,范围,地图,过滤器和缩小/折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用lambda,范围,地图,过滤和缩小/折叠等功能,计算1到1000之间的数字之和,这些数字可被5或3整除并打印结果.
Using the functions such as lambdas, range, map, filter and reduce/fold, calculate the sum of numbers between 1 and 1000 which are divisible by 5 or 3 and print the result.
推荐答案
我们可以执行以下操作:
We can do the following:
println((1..1000).filter{ it % 3 == 0 || it % 5 == 0 }.reduce{sum, element -> sum + element})
我们也可以使用如下所示的sum
来代替reduce:
Instead of reduce we could use sum
as well which would look like this:
println((1..1000).filter{ it % 3 == 0 || it % 5 == 0 }.sum())
这篇关于Kotlin:Lambda,范围,地图,过滤器和缩小/折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文