颠倒给定的 32 位无符号整数的二进制位
思路
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ans= 0;
for(int i = 0; i < 32; i++){
ans <<=1;
ans += n&1;
n>>=1;
}
return ans;
}
}
结果展示:
思路:
位运算,将输入的数进行反序颠倒,我们利用ans变量进行每一步答案的保存
将输入每次和1相与运算,也就是得到了输入数的最后一位 将其加入到答案中
将输入的最后一位右移舍去,将临时的ans左移一位
这样我么们就可以将输入从后向前不断获取最后一位的数值 再加到ans上面 从而获取到了逆序
注意:先左移,再相加最后一位 和先相加再左移的区别(后者可能最后一次循环跳出的时候多进行了一次左移)
public int reverseBits(int n) {
int ans= 0;
for(int i = 0; i < 32; i++){
ans += n&1;
if(i!=31)
ans <<=1;
n>>=1;
}
return ans;
}
换句话说,如果先相加后左移,要将最后一次舍去,答案才是正确的!!!!