From f6750f035ce1275a6ec1511fec9fbae2e0cd935f Mon Sep 17 00:00:00 2001 From: Ceiling_roof <48134466+ResilientSpring@users.noreply.github.com> Date: Mon, 10 Nov 2025 23:58:17 +0800 Subject: [PATCH 1/2] Committed on or around 2025/11/10 --- Miscellaneous/SOE/HappyNumber.java | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Miscellaneous/SOE/HappyNumber.java diff --git a/Miscellaneous/SOE/HappyNumber.java b/Miscellaneous/SOE/HappyNumber.java new file mode 100644 index 0000000..154f990 --- /dev/null +++ b/Miscellaneous/SOE/HappyNumber.java @@ -0,0 +1,10 @@ +package SOE; + +public class HappyNumber { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} From 0f4d0ad2aef284e0bd09628133e24b7afcf195ce Mon Sep 17 00:00:00 2001 From: Ceiling_roof <48134466+ResilientSpring@users.noreply.github.com> Date: Tue, 11 Nov 2025 12:29:44 +0800 Subject: [PATCH 2/2] Committed on or around 2025/11/11 --- Miscellaneous/SOE/HappyNumber.java | 43 +++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/Miscellaneous/SOE/HappyNumber.java b/Miscellaneous/SOE/HappyNumber.java index 154f990..4507bc9 100644 --- a/Miscellaneous/SOE/HappyNumber.java +++ b/Miscellaneous/SOE/HappyNumber.java @@ -1,10 +1,47 @@ package SOE; +import java.util.HashSet; +import java.util.Set; + public class HappyNumber { - public static void main(String[] args) { - // TODO Auto-generated method stub + // 計算各位數平方和 + static int next(int n) { + int sum = 0; + while (n > 0) { + int d = n % 10; + sum += d * d; + n /= 10; + } + return sum; + } + + // 遞迴版 isHappy() + static boolean isHappy(int n) { + return isHappyHelper(n, new HashSet<>()); + } + + // 遞迴輔助函式:傳遞 seen 集合 + private static boolean isHappyHelper(int n, Set seen) { + if (n == 1) + return true; // 終止條件:快樂數 + if (seen.contains(n)) + return false; // 終止條件:進入循環 + + seen.add(n); + return isHappyHelper(next(n), seen); + } - } + // 測試 + public static void main(String[] args) { + int[] nums = {1, 7, 19, 20, 25, 4}; + for (int n : nums) { + System.out.printf("%d -> %s%n", n, isHappy(n)); + } + } } + +// Source: https://chatgpt.com/c/69104fa3-4828-8321-ade1-f983f1f8c14c + +