Leetcode: Happy Number

Rachit Gupta
1 min readDec 26, 2016

--

  1. Find sum of squares of current number, add it to the set
  2. The set will keep track of sum of squares encountered
  3. Continue the process until a value repeats or if we find 1

Since we don’t know how many times the loop will execute we cannot determine the amount of space used or the time taken

class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while n != 1:
if n in s:
return False
s.add(n)
n = self.square_sum(n)
return True
def square_sum(self, n):
res = 0
while n:
v = n % 10
res += v * v
n = n / 10
return res

--

--