Преглед изворни кода

#feat:leetcode p1009题题解

yangyi пре 2 недеља
родитељ
комит
3a5f15f2f1
2 измењених фајлова са 73 додато и 0 уклоњено
  1. 31 0
      src/leetcode/p1009/Solution.java
  2. 42 0
      src/leetcode/p1009/SolutionTest.java

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

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

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

@@ -0,0 +1,42 @@
+package leetcode.p1009;
+
+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:15
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private final int n;
+    private final 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 n, int expected) {
+        this.n = n;
+        this.expected = expected;
+    }
+
+    @Test
+    public void bitwiseComplement() {
+        assertEquals(expected, solution.bitwiseComplement(n));
+    }
+}