A happy number is a number defined by the following process:
Return true
if n
is a happy number, and false
if not.
Example:
Input: n = 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
n
have any specific constraints (e.g. maximum value)?
n
is a positive integer.1
?
true
.To determine if a number is a happy number:
true
.false
.This way, we can detect cycles which indicate that the number will not reach 1.
#include <unordered_set>
class Solution {
public:
bool isHappy(int n) {
std::unordered_set<int> seen;
while (n != 1 && seen.find(n) == seen.end()) {
seen.insert(n);
n = getNext(n);
}
return n == 1;
}
private:
int getNext(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
n = n / 10;
sum += digit * digit;
}
return sum;
}
};
n
.This approach ensures that we can efficiently detect happy numbers and avoid infinite loops caused by cycles.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?