feat: add initial implementation of happy number solution
This commit is contained in:
parent
f98094172e
commit
0eb65c4ed3
7
202_happy_number/Cargo.lock
generated
Normal file
7
202_happy_number/Cargo.lock
generated
Normal file
@ -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"
|
6
202_happy_number/Cargo.toml
Normal file
6
202_happy_number/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "happy_number"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
29
202_happy_number/src/main.rs
Normal file
29
202_happy_number/src/main.rs
Normal file
@ -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::<i32>::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
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user