From a8e19d60bb371a44296134932b7470825c1fda6a Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Tue, 12 Jul 2022 14:08:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200202.=E5=BF=AB=E4=B9=90?= =?UTF-8?q?=E6=95=B0=20Rust=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0202.快乐数 Rust版本 --- problems/0202.快乐数.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 0bea0c72..2303765c 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -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 typedef struct HashNodeTag {