Solutin#2
public class Solution {
public boolean isHappy(int n) {
int slow = n;
int fast = figure(slow);
while (slow != fast) {
slow = figure(slow);
fast = figure(fast);
fast = figure(fast);
}
return slow == 1 ? true : false;
}
public int figure(int n) {
int result = 0;
while (n > 0) {
result += Math.pow(n % 10, 2);
n /= 10;
}
return result;
}
}
Solution#1
public class Solution {
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<Integer>();
int s = 0;
while(!set.contains(n)) {
set.add(n);
while(n > 0) {
s += Math.pow(n % 10, 2);
n = n / 10;
}
if (s == 1) return true;
n = s;
s = 0;
}
return false;
}
}
Problem#1
- 时间复杂度较高
- Floyd环检测算法