For this problem, the idea is to swap each digit with their corresponding 180-degree values and use Integer.parseInt to verify if it’s still a valid number. If yes, check also if it’s not equal to the original number as this may also affect the validity of the number.
class Solution {
fun isGood(num: Int): Boolean {
val s = num.toString()
val builder = StringBuilder()
val newValue = s.map {
when {
it == '0' || it == '1' || it == '8' -> it
it == '2' -> '5'
it == '5' -> '2'
it == '6' -> '9'
it == '9' -> '6'
else -> return false
}
}.joinToString("")
return try{
Integer.parseInt(newValue) != num
}catch(e: Exception){
false
}
}
fun rotatedDigits(N: Int): Int {
var ctr = 0
(2..N).forEach {
if(isGood(it)) {
ctr++
}
}
return ctr
}
}
Runtime: 256 ms, faster than 23.08% of Kotlin online submissions for Rotated Digits.
Memory Usage: 39.1 MB, less than 100.00% of Kotlin online submissions for Rotated Digits.