File tree 2 files changed +58
-0
lines changed
2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ use std:: collections:: HashSet ;
2
+
3
+ /// Write an algorithm to determine if a number `n` is happy.
4
+ ///
5
+ /// A happy number is a number defined by the following process:
6
+ ///
7
+ /// * Starting with any positive integer, replace the number by the sum of the
8
+ /// squares of its digits.
9
+ ///
10
+ /// * Repeat the process until the number equals 1 (where it will stay), or it
11
+ /// loops endlessly in a cycle which does not include 1.
12
+ ///
13
+ /// * Those numbers for which this process ends in 1 are happy.
14
+ ///
15
+ /// Return `true` if `n` is a happy number, and `false` if not.
16
+ struct Solution ;
17
+
18
+ impl Solution {
19
+
20
+ pub fn is_happy ( n : i32 ) -> bool {
21
+ let mut num = n;
22
+ let mut seen = HashSet :: new ( ) ;
23
+
24
+ while !seen. contains ( & num) && num != 1 {
25
+ seen. insert ( num) ;
26
+ num = num. to_string ( )
27
+ . split ( "" )
28
+ . map ( |d| d. parse :: < i32 > ( ) . unwrap_or_default ( ) )
29
+ . map ( |d| d * d)
30
+ . sum ( ) ;
31
+ }
32
+
33
+ num == 1
34
+ }
35
+
36
+ }
37
+
38
+ #[ cfg( test) ]
39
+ mod tests {
40
+ use super :: Solution ;
41
+
42
+ #[ test]
43
+ fn example_1 ( ) {
44
+ let n = 19 ;
45
+ let result = Solution :: is_happy ( n) ;
46
+ assert ! ( result) ;
47
+ }
48
+
49
+ #[ test]
50
+ fn example_2 ( ) {
51
+ let n = 2 ;
52
+ let result = Solution :: is_happy ( n) ;
53
+ assert ! ( !result) ;
54
+ }
55
+
56
+ }
Original file line number Diff line number Diff line change @@ -92,6 +92,8 @@ pub mod house_robber; // 198
92
92
pub mod binary_tree_right_side_view; // 199
93
93
pub mod number_of_islands; // 200
94
94
95
+ pub mod happy_number; // 202
96
+
95
97
pub mod reverse_linked_list; // 206
96
98
pub mod course_schedule; // 207
97
99
You can’t perform that action at this time.
0 commit comments