Created
April 3, 2020 04:00
-
-
Save slantview/464f96a7b6f437653755b4d119d25386 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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