diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 288ee4e..c8bf1df 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -126,4 +126,5 @@ mod p383_ransom_note; mod p290_word_pattern; mod p205_isomorphic_strings; mod p242_valid_anagram; -mod p49_group_anagrams; \ No newline at end of file +mod p49_group_anagrams; +mod p202_happy_number; \ No newline at end of file diff --git a/src/problem/p202_happy_number.rs b/src/problem/p202_happy_number.rs new file mode 100644 index 0000000..e2b33e0 --- /dev/null +++ b/src/problem/p202_happy_number.rs @@ -0,0 +1,54 @@ +/** + * [202] Happy Number + */ +pub struct Solution {} + +// submission codes start here +use std::{collections::HashSet, ops::Add}; + +impl Solution { + pub fn is_happy(n: i32) -> bool { + let mut s = HashSet::new(); + + let mut n = Solution::calculate_square(n); + + while n != 1 { + dbg!(n); + if s.contains(&n) { + return false; + } + + s.insert(n); + + n = Solution::calculate_square(n); + } + + true + } + + fn calculate_square(n: i32) -> i32 { + let mut n = n; + + let mut result = 0; + + while n != 0 { + result += (n % 10).pow(2); + n = n / 10; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_202() { + assert!(Solution::is_happy(19)); + assert!(!Solution::is_happy(2)); + } +}