diff --git a/202_happy_number/Cargo.lock b/202_happy_number/Cargo.lock new file mode 100644 index 0000000..237db44 --- /dev/null +++ b/202_happy_number/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "happy_number" +version = "0.1.0" diff --git a/202_happy_number/Cargo.toml b/202_happy_number/Cargo.toml new file mode 100644 index 0000000..ce73b9a --- /dev/null +++ b/202_happy_number/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "happy_number" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/202_happy_number/src/main.rs b/202_happy_number/src/main.rs new file mode 100644 index 0000000..45c50a4 --- /dev/null +++ b/202_happy_number/src/main.rs @@ -0,0 +1,29 @@ +use std::collections::HashSet; + +fn main() { + println!("Hello, world!"); +} + +struct Solution; + +impl Solution { + pub fn is_happy(mut n: i32) -> bool { + let mut numbers_shown = HashSet::::new(); + numbers_shown.insert(n); + + while n != 1 { + let mut new_n = 0; + for c in n.to_string().chars() { + new_n += (c as i32 - 48).pow(2); + } + n = new_n; + + if numbers_shown.contains(&n) { + return false; + } + numbers_shown.insert(n); + } + + true + } +}