We run until we see a repeated number and check if that is 1.
Say is an
digit number. So,
. Let
. The maximum value of
is when digits are all
‘s. In other words, the maximum value of
. Since
,
. So, one step of sum of digit squared reduces
to
. Thus the number of steps before we reach the cycle is
.
Time: , space:
.
class Solution:
def isHappy(self, n: int) -> bool:
def sum_of_digit_squared(n):
sq_sum = 0
while n > 0:
n, d = divmod(n, 10)
sq_sum += (d * d)
return sq_sum
seen = set()
while n not in seen:
seen.add(n)
n = sum_of_digit_squared(n)
return n == 1
The sequence of numbers: , always ends with a cycle. So, we can consider the sequence as a linked list with cycle and use slow and fast pointer to find cycle head and check if that is 1.
Time: , space:
.
class Solution:
def isHappy(self, n: int) -> bool:
def next(x):
sq_sum = 0
while x > 0:
x, d = divmod(x, 10)
sq_sum += (d * d)
return sq_sum
slow, fast = n, n
while True:
slow = next(slow)
fast = next(next(fast))
if slow == fast:
break
fast = n
while slow != fast:
slow = next(slow)
fast = next(fast)
return slow == 1
Here is a nice little paper on the problem.
Leave a comment