File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ ###Write an algorithm to determine if a number n is happy.
2
+ #
3
+ # A happy number is a number defined by the following process:
4
+ #
5
+ # Starting with any positive integer, replace the number by the sum of the squares of its digits.
6
+ # Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
7
+ # Those numbers for which this process ends in 1 are happy.
8
+ # Return true if n is a happy number, and false if not.
9
+ #
10
+ #
11
+ #
12
+ # Example 1:
13
+ #
14
+ # Input: n = 19
15
+ # Output: true
16
+ # Explanation:
17
+ # 12 + 92 = 82
18
+ # 82 + 22 = 68
19
+ # 62 + 82 = 100
20
+ # 12 + 02 + 02 = 1
21
+
22
+
23
+ n = 18
24
+
25
+ def happynumber (n ) -> bool :
26
+ seen = set ()
27
+
28
+ while n != 1 and n not in seen :
29
+ seen .add (n )
30
+ n = sum (int (i ) ** 2 for i in str (n ))
31
+
32
+ return n == 1
33
+
34
+
35
+
36
+ # if result == 1 -- > return True
37
+
38
+
39
+ print (happynumber (n ))
40
+
41
+
You can’t perform that action at this time.
0 commit comments