From 19a6a4e369277cd192f6b149b008ce2d0cba23a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lane=20Zhang=20=28=E5=BC=A0=E5=81=A5=29?= Date: Mon, 14 Oct 2024 10:00:24 +0800 Subject: [PATCH] =?UTF-8?q?Update=200202.=E5=BF=AB=E4=B9=90=E6=95=B0.md=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20Ruby=20=E7=89=88=E6=9C=AC=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0202.快乐数.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index 409a7471..39cb39fa 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -534,6 +534,30 @@ public class Solution { } ``` +### Ruby: + +```ruby +# @param {Integer} n +# @return {Boolean} +def is_happy(n) + @occurred_nums = Set.new + + while true + n = next_value(n) + + return true if n == 1 + + return false if @occurred_nums.include?(n) + + @occurred_nums << n + end +end + +def next_value(n) + n.to_s.chars.sum { |char| char.to_i ** 2 } +end +``` +