20240510 Finished

This commit is contained in:
jackfiled 2024-05-10 13:20:17 +08:00
parent e54e03c4f3
commit 14adc38396
2 changed files with 56 additions and 1 deletions

View File

@ -126,4 +126,5 @@ mod p383_ransom_note;
mod p290_word_pattern; mod p290_word_pattern;
mod p205_isomorphic_strings; mod p205_isomorphic_strings;
mod p242_valid_anagram; mod p242_valid_anagram;
mod p49_group_anagrams; mod p49_group_anagrams;
mod p202_happy_number;

View File

@ -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));
}
}