Skip to content

Instantly share code, notes, and snippets.

@jones
Created September 2, 2015 21:05
Show Gist options
  • Save jones/9f1976da4c53656a0c6c to your computer and use it in GitHub Desktop.
Save jones/9f1976da4c53656a0c6c to your computer and use it in GitHub Desktop.
Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Thos…
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
seenNums = set()
while n > 1 and (n not in seenNums):
seenNums.add(n)
n = sum(map(lambda x: x**2, map(int, list(str(n)))))
return n == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment