Javascript Soln


  • 0
    T

    Here's my solution in javascript, easy to understand, actually not sure how to go about analyzing the runtime of this
    because the outer loop will continue to run until it repeats, the inner loop has a runtime of O(n) where n is the number of digits of the input. Would love some help in analyzing the runtime out the outer loop

    /**
     * @param {number} n
     * @return {boolean}
     */
    var isHappy = function(n) {
        var seen = {};
        
        seen[n] = true;
    
        while (true) {
            n = n.toString()
                .split('')
                .map(function(digit){ return parseInt(digit, 10); })
                .reduce(function(total, digit) { return total + digit * digit; }, 0);
    
            if (n === 1) {
                return true;
            } else if (seen[n]) {
                return false;
            } else {
                seen[n] = true;
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.