class Solution {
private int notHappy(int n) {
int nextnum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
nextnum += d * d;
}
return nextnum;
}
public boolean isHappy(int n) {
Set<Integer> hap = new HashSet<Integer>();
while (n != 1 && !hap.contains(n)) {
hap.add(n);
n = notHappy(n);
}
return n == 1;
}
}
Using recursion.
Floyd's Cycle-Finding Algorithm
public int getNext(int n) {
int totalSum = 0;
while (n > 0) {
int d = n % 10;
n = n / 10;
totalSum += d * d;
}
return totalSum;
}
public boolean isHappy(int n) {
int slowRunner = n;
int fastRunner = getNext(n);
while (fastRunner != 1 && slowRunner != fastRunner) {
slowRunner = getNext(slowRunner);
fastRunner = getNext(getNext(fastRunner));
}
return fastRunner == 1;
}
사람들이 미쳤어요..^^