# 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; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up