Leetcode #202: Happy Number

Leetcode #202: Happy Number

Difficulty: Easy

This problem can be solved using recursion. Thought process:

  • Base case: Check if the number is 1. -OR- If the loop has been going on for a while.
  • Split the digits and sum it up (square of each digit)
  • Call the loop again until the value reaches 1 or it reaches the limit of loop (I set it to 100).

Link: Happy Number

/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n) {
    let happy = true;

    let loop = (n, c) => {
        if(n == 1) return;
        if(c> 100){
            happy = false;
            return;
        }

        let digits = n.toString().split('');
        let sum = 0;
        for(let i =0;i<digits.length; i++){
            sum += parseInt(digits[i]) * parseInt(digits[i]);

        }

        if(sum == 1){
            return;
        }else{
            loop(parseInt(sum), c+1);
        }
    }

    loop(n, 0);
    return happy;
};