# 0202. Happy Number ###### tags: `Leetcode` `Easy` `Detect Cycle` Link: https://leetcode.com/problems/happy-number/ ## 思路 ### 思路一 用HashSet找循环 只要有一个数重复出现,就说明进入到了循环里面 ### 思路二(重要!!) 快慢指针法找循环 ## Code ### 思路一 ```java= class Solution { public boolean isHappy(int n) { Set<Integer> set = new HashSet<>(); int res = compute(n); while(!set.contains(res)){ System.out.println(res); if(res == 1) return true; set.add(res); res = compute(res); } return false; } public static int compute(int n){ int res = 0; while(n != 0){ res+=(n%10)*(n%10); n/=10; } return res; } } ``` ### 思路二 ```java= class Solution { public boolean isHappy(int n) { int slowRunner = n; int fastRunner = compute(n); while(fastRunner!=1 && slowRunner!=fastRunner){ slowRunner = compute(slowRunner); fastRunner = compute(compute(fastRunner)); } return fastRunner == 1; } public static int compute(int n){ int res = 0; while(n != 0){ res+=(n%10)*(n%10); n/=10; } return res; } } ```