DEV Community

King coder
King coder

Posted on

Day 46 of DSA Problem Solving

Q1:- Happy Number

  • Write an algorithm to determine if a number n is happy or not.

Happy Number

A Happy Number is a special number with these steps:

  1. Start with any positive number.

  2. Take each digit of the number, square it (multiply it by itself), and add all those squares together to get a new number.

  3. Repeat this process with the new number.

  4. If after repeating this process many times, you get the number 1, then the original number is called a Happy Number.

  5. If you never get 1 and keep seeing the same numbers again and again, then the number is not happy (sometimes called sad).

Example

Start with 7:

- \(7^2 = 49\)  
- \(4^2 + 9^2 = 16 + 81 = 97\)  
- \(9^2 + 7^2 = 81 + 49 = 130\)  
- \(1^2 + 3^2 + 0^2 = 1 + 9 + 0 = 10\)  
- \(1^2 + 0^2 = 1 + 0 = 1\)  
Enter fullscreen mode Exit fullscreen mode
/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function(n, seen = new Set()) {
  if (n === 1) return true;
  if (n < 0 || seen.has(n)) return false;

  seen.add(n);

  let array_Of_Each_Char = String(n).split('');
  let sum = 0;

  for (let i = 0; i < array_Of_Each_Char.length; i++) {
    sum += Number(array_Of_Each_Char[i]) * Number(array_Of_Each_Char[i]);
  }

  n = Math.floor(sum);
  console.log(n);

  // ✅ Return the recursive call result
  return isHappy(n, seen);
};

// ✅ Test cases
console.log(isHappy(7));  // true
console.log(isHappy(2));  // false
console.log(isHappy(19)); // true
console.log(isHappy(4));  // false

Enter fullscreen mode Exit fullscreen mode

Top comments (0)