Article directory
topic
This question can actually be transformed into whether there is a ring;
because if n = 1 is finally obtained, no matter how you continue to calculate, it will still be 1, which means that a ring appears at the end. Return true
if the ring is not finally formed at n = 1 It is formed under the circumstances, indicating that there is a cycle, and returns false directly.
There is a ring:
There is no ring:
Method 1: Hash
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while( n != 1 && !set.contains(n)){
set.add(n);
n = getisHappy(n);
}
return n==1;
}
public int getisHappy(int n){
int res = 0;
while(n>0){
int temp = n%10;
res+= temp*temp;
n = n /10;
}
return res;
}
}
Method 2: Fast and slow pointers
class Solution {
public boolean isHappy(int n) {
int slow = n;
int fast = getisHappy(n);
while( fast != 1 && slow != fast ){
slow = getisHappy(slow);
fast = getisHappy(getisHappy(fast));
}
return fast==1;
}
public int getisHappy(int n){
int res = 0;
while(n>0){
int temp = n%10;
res+= temp*temp;
n = n /10;
}
return res;
}
}