题目
https://leetcode-cn.com/problems/reverse-bits/
我的方法
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int[] tmp=new int[32];
for(int i=0;i<32;i++){
tmp[i]=n&1;
n=n>>>1;
}
int res=0;
for(int i=0;i<32;i++){
res=res<<1;
res=res|(tmp[i]&1);
}
return res;
}
}
方法1
思路
代码
public class Solution {
public int reverseBits(int n) {
int rev = 0;
for (int i = 0; i < 32 && n != 0; ++i) {
rev |= (n & 1) << (31 - i);
n >>>= 1;
}
return rev;
}
}
复杂度
时间复杂度:O(logn)。
空间复杂度:O(1)。
方法2
分治。略。