Happy Number

This easy problem looks simple at first but it gets very tricky specially when finding out if your loop already started in an endless loop. I did try a couple of ideas without using a list to keep track of previous sums but all didn’t work. Eventually I ended up using a mutableList to maintain a list of previous sums so I can look up and see if the new sum has been solved before. If it is, then it means we entered into an endless loop already.

class Solution {
    
    val ssq: (Int) -> Int = {
        var x = it
        var sum = 0
        while(x != 0){
            sum += Math.pow((x % 10).toDouble(), 2.0).toInt()
            x = x / 10
        }
        
        sum
    }
    
    fun isHappy(n: Int): Boolean {
        var x = n
        var start = 0
        var prevs = mutableListOf<Int>()
        while(x != 1){
            x = ssq(x)  
            if(x in prevs) break
            prevs.add(x)
        }
        
        return x == 1
    }
}
Runtime: 140 ms, faster than 67.19% of Kotlin online submissions for Happy Number.
Memory Usage: 31.2 MB, less than 100.00% of Kotlin online submissions for Happy Number.
comments powered by Disqus