题目信息

解题思路

代码

With Hashset or Hashtable

  class Solution:
	  def isHappy(self, n: int) -> bool:
		  cache = {}
		  while n != 1:
			  s = 0
			  while n != 0:
				  a = n % 10
				  s += a * a
				  n = n // 10
			  if s == 1:
				  return True
			  if cache.get(s) is not None:
				  return False
			  else:
				  cache[s] = 1
			  n = s
		  return True
	  ```

### Without Hashset

```python
  # from neetcode.io
  class Solution:
	  def isHappy(self, n: int) -> bool:
		  slow, fast = n, self.sumSquareDigits(n)
  
		  while slow != fast:
			  fast = self.sumSquareDigits(fast)
			  fast = self.sumSquareDigits(fast)
			  slow = self.sumSquareDigits(slow)
  
		  return True if fast == 1 else False
  
	  def sumSquareDigits(self, n):
		  output = 0
		  while n:
			  output += (n % 10) ** 2
			  n = n // 10
		  return output