feat: 202_happy_number

This commit is contained in:
SquidSpirit 2025-08-17 22:41:41 +08:00
parent a916917fae
commit cf6277cbec
3 changed files with 42 additions and 0 deletions

7
202_happy_number/Cargo.lock generated Normal file
View 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"

View File

@ -0,0 +1,6 @@
[package]
name = "happy_number"
version = "0.1.0"
edition = "2024"
[dependencies]

View 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
}
}