kt: add «2698. Find the Punishment Number of an Integer»

URL:	https://leetcode.com/problems/find-the-punishment-number-of-an-integer/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-15 11:14:29 +01:00
parent e0a3d6a21c
commit dcfa7705c5
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,28 @@
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
}
}
}