Skip to content

Commit e81f446

Browse files
committed
Create happy-number.py
1 parent 9e83351 commit e81f446

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Python/happy-number.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Time: O(k), where k is the steps to be happy number
2+
# Space: O(k)
3+
#
4+
# Write an algorithm to determine if a number is "happy".
5+
#
6+
# A happy number is a number defined by the following process:
7+
# Starting with any positive integer, replace the number by the sum
8+
# of the squares of its digits, and repeat the process until
9+
# the number equals 1 (where it will stay), or it loops endlessly
10+
# in a cycle which does not include 1. Those numbers for which
11+
# this process ends in 1 are happy numbers.
12+
#
13+
# Example: 19 is a happy number
14+
#
15+
# 1^2 + 9^2 = 82
16+
# 8^2 + 2^2 = 68
17+
# 6^2 + 8^2 = 100
18+
# 1^2 + 0^2 + 0^2 = 1
19+
#
20+
class Solution:
21+
# @param {integer} n
22+
# @return {boolean}
23+
def isHappy(self, n):
24+
lookup = {}
25+
while n != 1 and n not in lookup:
26+
lookup[n] = True
27+
n = self.nextNumber(n)
28+
return n == 1
29+
30+
def nextNumber(self, n):
31+
new = 0
32+
for char in str(n):
33+
new += int(char)**2
34+
return new

0 commit comments

Comments
 (0)