202. 快乐数

  1. func isHappy(n int) bool {
  2. slow, fast := n, next(n)
  3. for fast != 1 && fast != slow {
  4. slow = next(slow)
  5. fast = next(next(fast)) // 1的各位平方和还是1, 所以不会跳过
  6. }
  7. return fast == 1
  8. }
  9. func next(n int) int {
  10. sum := 0
  11. for n > 0 {
  12. sum += (n % 10) * (n % 10)
  13. n /= 10
  14. }
  15. return sum
  16. }