Happy Number LeetCode Solution

Here, We see Happy Number LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Happy Number LeetCode Solution

Happy Number LeetCode Solution

Problem Statement

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

happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2:
Input: n = 2
Output: false

Happy Number Leetcode Solution C++

class Solution {
public:
    int solve(int n) {
        int sum = 0;
        while(n > 0) {
			int r = n%10;
            sum += r*r;
            n /= 10;
        }
        return sum;
    }

    bool isHappy(int n) {
        int slow = n, fast = n;
        do {
            slow = solve(slow);
            fast = solve(solve(fast));
            if(fast == 1) return 1;
        } while(slow != fast);
        return 0;
    }
};
Code language: C++ (cpp)

Happy Number Leetcode Solution Java

class Solution {
    public boolean isHappy(int n) {
        if(n<=0) return false;
        while(true){
            int sum=0;
            while(n!=0){
              sum+=(n%10)*(n%10);
              n=n/10;
            }
            if(sum/10==0){
               if(sum==1||sum==7) return true;
               else return false;
            }
            n=sum;
        }
    }
}
Code language: Java (java)

Happy Number Leetcode Solution JavaScript

var isHappy = function(n) {
    var seen = {};
    while (n !== 1 && !seen[n]) {
        seen[n] = true;
        n = sumOfSquares(n);
    }
    return n === 1 ? true : false;
};

function sumOfSquares(numString) {
    return numString.toString().split('').reduce(function(sum, num) {
        return sum + Math.pow(num, 2);
    }, 0);
};
Code language: JavaScript (javascript)

Happy Number Leetcode Solution Python

class Solution(object):
    def isHappy(self, n):
        total = 0
        for digit_str in str(n):
            digit = int(digit_str)
            total += digit * digit

        if total == 1 or total == 7:
            return True
        else:
            if total < 10 or total == 0:
                return False
            else:
                return self.isHappy(total)
Code language: Python (python)
Scroll to Top