mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0202.快乐数 Rust版本
添加 0202.快乐数 Rust版本
This commit is contained in:
@ -315,6 +315,36 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Rust:
|
||||||
|
```Rust
|
||||||
|
use std::collections::HashSet;
|
||||||
|
impl Solution {
|
||||||
|
pub fn get_sum(mut n: i32) -> i32 {
|
||||||
|
let mut sum = 0;
|
||||||
|
while n > 0 {
|
||||||
|
sum += (n % 10) * (n % 10);
|
||||||
|
n /= 10;
|
||||||
|
}
|
||||||
|
sum
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_happy(n: i32) -> bool {
|
||||||
|
let mut n = n;
|
||||||
|
let mut set = HashSet::new();
|
||||||
|
loop {
|
||||||
|
let sum = Self::get_sum(n);
|
||||||
|
if sum == 1 {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if set.contains(&sum) {
|
||||||
|
return false;
|
||||||
|
} else { set.insert(sum); }
|
||||||
|
n = sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
C:
|
C:
|
||||||
```C
|
```C
|
||||||
typedef struct HashNodeTag {
|
typedef struct HashNodeTag {
|
||||||
|
Reference in New Issue
Block a user