Forráskód Böngészése

#feat:leetcode p476题题解

yangyi 2 hete
szülő
commit
4c7f37907e
2 módosított fájl, 73 hozzáadás és 0 törlés
  1. 31 0
      src/leetcode/p476/Solution.java
  2. 42 0
      src/leetcode/p476/SolutionTest.java

+ 31 - 0
src/leetcode/p476/Solution.java

@@ -0,0 +1,31 @@
+package leetcode.p476;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/11 20:41
+ * @Description: https://leetcode.cn/problems/number-complement/description/
+ * 476. 数字的补数
+ */
+public class Solution {
+    public int findComplement(int num) {
+        if (num == 0) {
+            return 1;
+        }
+        /**
+         * 异或操作可以实现按位取反
+         * 先找最高位的1,后续消除前导零的影响需要用到
+         *
+         */
+        int count = 0;
+        int temp = num;
+        while(temp != 0){
+            count++;
+            temp >>= 1;
+        }
+        //得到与最高位长度一致的连续的二进制1
+        temp = (1 << count) - 1;
+        return num ^ temp;
+    }
+}

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

@@ -0,0 +1,42 @@
+package leetcode.p476;
+
+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/11 20:42
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int num;
+    private int expected;
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {5,2},
+                {7,0},
+                {10,5},
+                {0,1},
+        });
+    }
+    public SolutionTest(int num, int expected) {
+        this.num = num;
+        this.expected = expected;
+    }
+
+    @Test
+    public void findComplement() {
+        assertEquals(expected, solution.findComplement(num));
+    }
+}