方法一:dfs
class Solution { public boolean isHappy(int n) { dfs(n); return flag; } boolean flag = false; Set<Integer> set = new HashSet<>(); public void dfs(int n) { if(n == 1) { flag = true; return; } if(set.contains(n)) return; set.add(n); int res = 0; while(n != 0) { int k = n % 10; res += k * k; n /= 10; } dfs(res); } }
方法二:快慢指针
使用“快慢指针”思想找出循环:“快指针”每次走两步,“慢指针”每次走一步,当二者相等时,即为一个循环周期。此时,判断是不是因为1引起的循环,是的话就是快乐数,否则不是快乐数。
class Solution { public boolean isHappy(int n) { int slow = happy(n); int fast = happy(n); do{ slow = happy(slow); fast = happy(happy(fast)); }while(slow != fast); return slow == 1 ? true : false; } public int happy(int n) { int sum = 0; while(n != 0) { sum += (n%10) * (n%10); n /= 10; } return sum; } }