|
|
@@ -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);
|
|
|
+ }
|
|
|
+}
|