LeetCode-探索-初级算法-其他-3. 颠倒二进制位(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 颠倒二进制位
-
语言:java
-
思路:除了获取每一位,然后直接位运算和最开头的替换,暂时没想到比较好的方法.
-
参考代码1(1ms):
https://blog.csdn.net/qq_33330687/article/details/81903145
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int result = 0; int i = 0; while(i<32){ int temp = n&1; //得到最后一位 0或者1 n = n>>1; //右移动1位 result = result<<1|temp; //首先把二进制往左边移动1位,然后|操作,1010左移 10100|1==10101 i++; } return result; } }
-
参考代码2(1ms):没想到参考答案的想法和我是一样的,只不过我没有把替换的位运算方式想好
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int result = 0; for (int i = 0; i < 32; i++) { // 1. 将给定的二进制数,由低到高位逐个取出 // 1.1 右移 i 位, int tmp = n >> i; // 1.2 取有效位 tmp = tmp & 1; // 2. 然后通过位运算将其放置到反转后的位置. tmp = tmp << (31 - i); // 3. 将上述结果再次通过运算结合到一起 result |= tmp; } return result; } }
-
参考后重写(1ms):其实颠倒的问题本质就是数字1的位置颠倒.
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int change; int res = 0; for(int i = 0; i < 32; ++i){ change = (n >> i) & 1;//获取第i位,从0开始作下标 change = change << (31-i); res |= change;//完成第i位替换 } return res; } }