# 202. Happy Number

Write an algorithm to determine if a number 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, and 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 numbers.

Example:

``````Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
``````

Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4

``````class Solution {
public:
bool isHappy(int n) {
unordered_set<int> st;
while (n != 1) {
int sum = 0;
while (n) {
sum += (n % 10) * (n % 10);
n /= 10;
}
n = sum;
if (st.count(n)) break;
st.insert(n);
}
return n == 1;
}
};
``````

``````class Solution {
public:
bool isHappy(int n) {
while (n != 1 && n != 4) {
int sum = 0;
while (n) {
sum += (n % 10) * (n % 10);
n /= 10;
}
n = sum;
}
return n == 1;
}
};
``````

``````class Solution {
public:
bool isHappy(int n) {
int slow = n, fast = n;
while (true) {
slow = findNext(slow);
fast = findNext(fast);
fast = findNext(fast);
if (slow == fast) break;
}
return slow == 1;
}
int findNext(int n) {
int res = 0;
while (n > 0) {
res += (n % 10) * (n % 10);
n /= 10;
}
return res;
}
};
``````

Ugly Number

https://leetcode.com/problems/happy-number/

https://leetcode.com/problems/happy-number/discuss/56913/Beat-90-Fast-Easy-Understand-Java-Solution-with-Brief-Explanation

https://leetcode.com/problems/happy-number/discuss/56917/My-solution-in-C(-O(1)-space-and-no-magic-math-property-involved-)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation