Skip to content
LC-0202 Easy LeetCode

202. Happy Number

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 58% Topics: Hash Table, Math, Two Pointers
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(k), where k is the steps to be happy number
# Space: O(k)

class Solution(object):
    # @param {integer} n
    # @return {boolean}
    def isHappy(self, n):
        lookup = {}
        while n != 1 and n not in lookup:
            lookup[n] = True
            n = self.nextNumber(n)
        return n == 1

    def nextNumber(self, n):
        new = 0
        for char in str(n):
            new += int(char)**2
        return new

Solution from kamyu104/LeetCode-Solutions · MIT