Skip to content

Commit

Permalink
Added happy number solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 28, 2024
1 parent 62a0dd1 commit 0186c31
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ programming challenges completed in other languages.
- [Ransom Note](https://leetcode.com/problems/ransom-note)
- [Word Pattern](https://leetcode.com/problems/word-pattern)
- [Valid Anagram](https://leetcode.com/problems/valid-anagram)
- [Happy Number](https://leetcode.com/problems/happy-number)

#### Medium

Expand Down
45 changes: 45 additions & 0 deletions src/leetcode/happy_number.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use std::collections::HashSet;

fn get_digit_square_sum(mut n: u64) -> u64 {
let mut sum = 0;
while n > 0 {
sum += (n % 10).pow(2);
n /= 10;
}
sum
}

pub fn is_happy(n: i32) -> bool {
let mut seen = HashSet::new();
let mut curr = get_digit_square_sum(n as u64);
while seen.insert(curr) {
if curr == 1 {
return true;
}
curr = get_digit_square_sum(curr);
}
false
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn identifies_happy_numbers() {
assert!(is_happy(19))
}

#[test]
fn identifies_unhappy_numbers() {
assert!(!is_happy(2))
}

#[test]
fn calculates_sum_square_of_digits() {
assert_eq!(82, get_digit_square_sum(19));
assert_eq!(68, get_digit_square_sum(82));
assert_eq!(100, get_digit_square_sum(68));
assert_eq!(1, get_digit_square_sum(100))
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ mod grid_illumination;
mod group_anagrams;
mod guess_number;
mod hamming_distance;
mod happy_number;
mod hour_glass_sum;
mod intersection_two;
mod invert_tree;
Expand Down

0 comments on commit 0186c31

Please sign in to comment.