Prechádzať zdrojové kódy

#feat:leetcode p202题题解

yangyi 2 týždňov pred
rodič
commit
f887b1d205

+ 56 - 0
src/leetcode/p202/Solution.java

@@ -0,0 +1,56 @@
+package leetcode.p202;
+
+import java.util.HashSet;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/8 16:43
+ * @Description: https://leetcode.cn/problems/happy-number/description/
+ * 202. 快乐数
+ */
+public class Solution {
+    public boolean isHappy(int n) {
+        //快乐数计算结果不会重复
+        //重复的就是不是快乐数,也就是计算会出现周期(有环就可以考虑使用快慢指针)
+        int slow = n;
+        int fast = n;
+        do{
+            slow = cal(slow);
+            fast = cal(cal(fast));
+        }while (slow != fast);
+        //重复的地方可能是1,也可能是其他数
+        return slow == 1;
+    }
+    private int cal(int n){
+        int res = 0;
+        while (n > 0){
+            res += (n % 10) * (n % 10);
+            n /= 10;
+        }
+            return res;
+    }
+
+    /**
+     * 哈希表解法
+     * @param n
+     * @return boolean
+     * @description:
+     * @author: 杨逸
+     * @data:2026/03/08 16:51:25
+     * @since 1.0.0
+     */
+    private boolean hashSolution(int n){
+        //快乐数计算结果不会重复
+        //哈希表,记录已经出现过的数
+        HashSet<Integer> set = new HashSet<>();
+        while(!set.contains(n) || n != 1){
+            n = cal(n);
+            if (set.contains(n))return false;
+            set.add(n);
+        }
+        return true;
+    }
+
+}

+ 42 - 0
src/leetcode/p202/SolutionTest.java

@@ -0,0 +1,42 @@
+package leetcode.p202;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/8 16:49
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int n;
+    private boolean expected;
+
+    public SolutionTest(int n, boolean expected) {
+        this.n = n;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data() {
+        return Arrays.asList(new Object[][]{
+                {19,true},
+                {2,false},
+        });
+    }
+
+    @Test
+    public void isHappy() {
+        boolean result = solution.isHappy(n);
+        assertEquals(expected,result);
+    }
+}