题目描述:

image.png

题解:

用哈希集合检测循环

image.png
image.png

  1. def isHappy(self, n: int) -> bool:
  2. def get_next(n):
  3. total_sum = 0
  4. while n > 0:
  5. n, digit = divmod(n, 10)
  6. total_sum += digit ** 2
  7. return total_sum
  8. seen = set()
  9. while n != 1 and n not in seen:
  10. seen.add(n)
  11. n = get_next(n)
  12. return n == 1