How to check if a number is a happy number in Kotlin

1 Answer

0 votes
// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

fun sumOfSquares(n: Int): Int =
    n.toString()
        .map { it.digitToInt() }
        .sumOf { it * it }

fun isHappy(n: Int): Boolean {
    val seen = mutableSetOf<Int>()
    var x = n

    while (x != 1 && x !in seen) {
        seen += x
        x = sumOfSquares(x)
    }

    return x == 1
}

fun main() {
    val num = 82

    if (isHappy(num)) {
        println("$num is a happy number")
    } else {
        println("$num is NOT a happy number")
    }
}



/*
run:

82 is a happy number

*/

 



answered Feb 24 by avibootz
edited Feb 24 by avibootz
...