Ver Fonte

#feat:leetcode p190题题解

yangyi há 2 semanas atrás
pai
commit
4dd4986694
2 ficheiros alterados com 97 adições e 0 exclusões
  1. 59 0
      src/leetcode/p190/Solution.java
  2. 38 0
      src/leetcode/p190/SolutionTest.java

+ 59 - 0
src/leetcode/p190/Solution.java

@@ -0,0 +1,59 @@
+package leetcode.p190;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/10 10:57
+ * @Description: https://leetcode.cn/problems/reverse-bits/description/
+ * 190. 颠倒二进制位
+ */
+public class Solution {
+    /**
+     * 辅助对子部分进行位移的变量
+     */
+    private static final int m0 = 0x55555555; // 01010101 ...
+    private static final int m1 = 0x33333333; // 00110011 ...
+    private static final int m2 = 0x0f0f0f0f; // 00001111 ...
+    private static final int m3 = 0x00ff00ff; // 00000000111111110000000011111111
+    public int reverseBits(int n) {
+        /**
+         * 位运算解法
+         * 分治法用位运算优化
+         * 左移和右移是对子部分的处理
+         * 或运算是对子部分进行合并
+         */
+        n = n>>>1&m0 | (n&m0)<<1; // 交换相邻位
+        n = n>>>2&m1 | (n&m1)<<2; // 两个两个交换
+        n = n>>>4&m2 | (n&m2)<<4; // 四个四个交换
+        n = n>>>8&m3 | (n&m3)<<8; // 八个八个交换
+        return n>>>16 | n<<16;    // 交换高低 16 位
+    }
+
+    /**
+     * 暴力解法
+     * @param n
+     * @return int
+     * @description:
+     * @author: 杨逸
+     * @data:2026/03/10 11:15:49
+     * @since 1.0.0
+     */
+    private int m(int n){
+        String s = Integer.toBinaryString(n);
+        while(s.length() < 32) {
+            s = "0"  + s;
+        }
+        char[] chars = s.toCharArray();
+        int left  =0;
+        int right = 31;
+        while(left < right) {
+            char temp = chars[left];
+            chars[left] = chars[right];
+            chars[right] = temp;
+            left++;
+            right--;
+        }
+        return Integer.valueOf(String.valueOf(chars), 2);
+    }
+}

+ 38 - 0
src/leetcode/p190/SolutionTest.java

@@ -0,0 +1,38 @@
+package leetcode.p190;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/10 10:58
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int n;
+    private int expected;
+
+    public SolutionTest(int n, int expected) {
+        this.n = n;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {43261596,964176192},
+                {2147483644,1073741822},
+        });
+    }
+
+    @Test
+    public void reverseBits() {
+    }
+}