Skip to content

Commit e77c6ea

Browse files
committed
Added Happy Number
1 parent c946454 commit e77c6ea

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/happy_number.rs

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ pub mod house_robber; // 198
9292
pub mod binary_tree_right_side_view; // 199
9393
pub mod number_of_islands; // 200
9494

95+
pub mod happy_number; // 202
96+
9597
pub mod reverse_linked_list; // 206
9698
pub mod course_schedule; // 207
9799

0 commit comments

Comments
 (0)