Skip to content

Commit a8e19d6

Browse files
committed
添加 0202.快乐数 Rust版本
添加 0202.快乐数 Rust版本
1 parent a29b52c commit a8e19d6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

problems/0202.快乐数.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,36 @@ class Solution {
315315
}
316316
```
317317

318+
Rust:
319+
```Rust
320+
use std::collections::HashSet;
321+
impl Solution {
322+
pub fn get_sum(mut n: i32) -> i32 {
323+
let mut sum = 0;
324+
while n > 0 {
325+
sum += (n % 10) * (n % 10);
326+
n /= 10;
327+
}
328+
sum
329+
}
330+
331+
pub fn is_happy(n: i32) -> bool {
332+
let mut n = n;
333+
let mut set = HashSet::new();
334+
loop {
335+
let sum = Self::get_sum(n);
336+
if sum == 1 {
337+
return true;
338+
}
339+
if set.contains(&sum) {
340+
return false;
341+
} else { set.insert(sum); }
342+
n = sum;
343+
}
344+
}
345+
}
346+
```
347+
318348
C:
319349
```C
320350
typedef struct HashNodeTag {

0 commit comments

Comments
 (0)