DEV Community

Cover image for LeetCode DSA Series #3: 202. Happy Number
David Babalola
David Babalola

Posted on

LeetCode DSA Series #3: 202. Happy Number

This is also an easy problem. Find it here.

Here's my solution to the problem.

class Solution:
    def isHappy(self, n: int) -> bool:
        new_n = n
        seen = set()

        while True:
            sums = 0
            for i in str(new_n):
                sums += int(i) * int(i)
            new_n = sums

            if new_n == 1:
                return True

            if new_n in seen:
                return False
            else:
                seen.add(new_n)
        return False

Enter fullscreen mode Exit fullscreen mode

The time and space complexity is O(log n).

Is there a better way to do this? Please let me know.

Top comments (0)