Happy Number
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 = 1Analysis
Solution
class Solution {
public boolean isHappy(int n) {
long t = n;
Set<Long> seen = new HashSet<Long>();
while (seen.add(t)) {
t = process(t);
if (t == 1) {
return true;
}
}
return false;
}
private long process(long n) {
long res = 0;
while (n > 0) {
long rem = n % 10;
res += rem * rem;
n /= 10;
}
return res;
}
}Reference
Last updated