0202. Happy Number
Description
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1ac
Last updated
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1Last updated
**Input:** n = 2
**Output:** falseclass Solution {
public boolean isHappy(int n) {
// edge cases
if (n <= 0) return false;
return recur(n, new HashSet<Integer>());
}
private boolean recur(int n, Set<Integer> set) {
// exit
if (n == 1) return true;
if (set.contains(n)) return false; // meet loop
set.add(n);
int m = 0;
while (n > 0) {
m += Math.pow(n % 10, 2);
n /= 10;
}
// next
return recur(m, set);
}
}