Last updated on March 9th, 2025 at 09:46 pm
Here, we see a Happy Number LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Hash Table, Math
Companies
Airbnb, Twitter, Uber
Level of Question
Easy

Happy Number LeetCode Solution
Table of Contents
1. Problem Statement
Write an algorithm to determine if a number n is happy.
A 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
2. Coding Pattern Used in Solution
The coding pattern used in the provided code is Fast & Slow Pointers. This pattern is commonly used to detect cycles in linked lists or sequences. In this case, the problem involves detecting cycles in the sequence of numbers generated by repeatedly summing the squares of the digits of a number.
3. Code Implementation in Different Languages
3.1 Happy Number 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; } };
3.2 Happy Number 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; } } }
3.3 Happy Number 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); };
3.4 Happy Number 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)
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n) | O(1) |
Java | O(n) | O(1) |
JavaScript | O(n) | O(1) |
Python | O(n) | O(1) |
where n is the number of digits in the input number.