URL: https://leetcode.com/problems/find-the-punishment-number-of-an-integer/ Signed-off-by: Matej Focko <me@mfocko.xyz>
28 lines
678 B
Kotlin
28 lines
678 B
Kotlin
class Solution {
|
|
companion object {
|
|
private val PARTITIONS: List<Int> = listOf(10, 100, 1000)
|
|
}
|
|
|
|
private fun canPartition(
|
|
num: Int,
|
|
target: Int,
|
|
): Boolean =
|
|
when {
|
|
target < 0 || num < target -> false
|
|
num == target -> true
|
|
else ->
|
|
PARTITIONS.any { it ->
|
|
canPartition(num / it, target - num % it)
|
|
}
|
|
}
|
|
|
|
fun punishmentNumber(n: Int): Int =
|
|
(1..n).asSequence().sumOf {
|
|
val square = it * it
|
|
|
|
when {
|
|
canPartition(square, it) -> square
|
|
else -> 0
|
|
}
|
|
}
|
|
}
|