Skip to content

Commit aea3928

Browse files
committed
Happy Number
1 parent ea163b2 commit aea3928

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Happy_Number.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Write an algorithm to determine if a number is "happy".
2+
#
3+
# A happy number is a number defined by the following process: Starting with
4+
# any positive integer, replace the number by the sum of the squares of its digits,
5+
# and repeat the process until the number equals 1 (where it will stay), or it loops endlessly
6+
# in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
7+
#
8+
# Example:
9+
#
10+
# Input: 19
11+
# Output: true
12+
# Explanation:
13+
# 12 + 92 = 82
14+
# 82 + 22 = 68
15+
# 62 + 82 = 100
16+
# 12 + 02 + 02 = 1
17+
18+
19+
class Solution:
20+
def isHappy(self, n):
21+
slow = n
22+
fast = self.getNum(n)
23+
24+
while fast != 1 and slow != fast:
25+
slow = self.getNum(slow)
26+
fast = self.getNum(self.getNum(fast))
27+
28+
return fast == 1
29+
30+
def getNum(self, num):
31+
res = 0
32+
while num > 0:
33+
res += (num % 10) ** 2
34+
num = num // 10
35+
return res

0 commit comments

Comments
 (0)