Skip to content

Instantly share code, notes, and snippets.

@slantview
Created April 3, 2020 04:00
Show Gist options
  • Save slantview/464f96a7b6f437653755b4d119d25386 to your computer and use it in GitHub Desktop.
Save slantview/464f96a7b6f437653755b4d119d25386 to your computer and use it in GitHub Desktop.
use std::collections::HashSet;
impl Solution {
pub fn is_happy(n: i32) -> bool {
if n == 1 { return true; }
let mut cur: i32 = n;
let mut seen: HashSet<i32> = HashSet::new();
loop {
// Split into array, fold into values and reset as cur.
let result = cur.to_string()
.chars().map(|d|
d.to_digit(10).unwrap() as i32
)
.fold(0, |acc, x| acc + x.pow(2));
if result == 1 {
return true;
}
if !seen.insert(result) {
return false;
}
cur = result;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment