📝 Problem Details
- Title:
200. Happy Number
- Link: https://leetcode.com/problems/happy-number/
- Difficulty: Easy
- Tags/Categories: Math Hashmap
Happy Number: 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 if the number does not result in 1, it will loop endlessly (a cycle) numbers for which this process ends in 1 are happy return true if
n
is a happy number, and false if not
💡 Explanation of Solution
1. use a hashset to track all previously seen numbers
2. repeatedly compute the sum of the squares of the digits of the current number
- convert n to a string
- iterate through each character in the string
- convert char to integer
- sum the squares of the digits
3. if we encounter 1, return true (its a happy number)
4. if we encounter a number already in the set, return false (cycle detected)
⌛ Complexity Analysis
Time Complexity: O(log n)
Space Complexity: O(log n)
💻 Implementation of Solution
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> seen;
while (n != 1) {
if (seen.count(n)) return false; // Cycle detected
seen.insert(n);
int newNum = 0;
string numStr = to_string(n); // Convert to string
for (char c : numStr) {
int digit = c - '0'; // Convert character to integer
newNum += digit * digit;
}
n = newNum;
}
return true; // If we reach 1, it's a happy number
}
};