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:
parent
e0a3d6a21c
commit
dcfa7705c5
1 changed files with 28 additions and 0 deletions
28
kt/find-the-punishment-number-of-an-integer.kt
Normal file
28
kt/find-the-punishment-number-of-an-integer.kt
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue