File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments