LeetCode 202: Happy Number Solution
Master LeetCode problem 202 (Happy Number), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
202. Happy Number
Problem Explanation
Explanation
To solve this problem, we can use a set to keep track of the numbers we have encountered while calculating the sum of the squares of digits. If we encounter a number that we have already seen, it means we are in a cycle and the number is not happy. If we reach 1, the number is happy. We keep iterating this process until we reach either 1 or a number we have seen before.
Algorithm:
- Initialize an empty set to store seen numbers.
- While the number is not 1 and the number is not in the set:
- Calculate the sum of the squares of digits.
- If the sum is 1, return true.
- Otherwise, add the sum to the set and update the number.
- If the number is not 1, return false.
Time Complexity: O(log n) - Each step calculates the sum of squares of digits which involves log n digits in the number n. Space Complexity: O(log n) - The space used by the set to store seen numbers.
Solution Code
class Solution {
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
n = sum;
}
return n == 1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 202 (Happy Number)?
This page provides optimized solutions for LeetCode problem 202 (Happy Number) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 202 (Happy Number)?
The time complexity for LeetCode 202 (Happy Number) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 202 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 202 in Java, C++, or Python.