Skip to content

Commit e77bb97

Browse files
committed
solve #202
1 parent 7aed3da commit e77bb97

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,4 @@ mod n0198_house_robber;
169169
mod n0199_binary_tree_right_side_view;
170170
mod n0200_number_of_islands;
171171
mod n0201_bitwise_and_of_numbers_range;
172+
mod n0202_happy_number;

src/n0202_happy_number.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* [202] Happy Number
3+
*
4+
* Write an algorithm to determine if a number is "happy".
5+
*
6+
* A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
7+
*
8+
* Example:
9+
*
10+
*
11+
* Input: 19
12+
* Output: true
13+
* Explanation:
14+
* 1^2 + 9^2 = 82
15+
* 8^2 + 2^2 = 68
16+
* 6^2 + 8^2 = 100
17+
* 1^2 + 0^2 + 0^2 = 1
18+
*
19+
*/
20+
pub struct Solution {}
21+
22+
// submission codes start here
23+
24+
use std::collections::HashSet;
25+
impl Solution {
26+
pub fn is_happy(n: i32) -> bool {
27+
let mut set = HashSet::new();
28+
let mut n = n;
29+
loop {
30+
set.insert(n);
31+
let temp = Solution::next(n);
32+
if temp == 1 {
33+
return true
34+
}
35+
if !set.insert(temp) {
36+
return false
37+
}
38+
n = temp
39+
}
40+
return false
41+
}
42+
43+
fn next(n: i32) -> i32 {
44+
let mut res = 0;
45+
let mut n = n;
46+
while n != 0 {
47+
res += (n % 10).pow(2);
48+
n = n / 10;
49+
}
50+
res
51+
}
52+
}
53+
54+
// submission codes end
55+
56+
#[cfg(test)]
57+
mod tests {
58+
use super::*;
59+
60+
#[test]
61+
fn test_202() {
62+
assert_eq!(Solution::is_happy(19), true);
63+
assert_eq!(Solution::is_happy(235123), false);
64+
}
65+
}

0 commit comments

Comments
 (0)