题:https://leetcode.com/problems/reverse-bits/
题目大意
将32位的数,二进制翻转。
解题思路
解法和 将int a =123,翻转的思路 相同。
int b= 0;
while(a>0){
b = b*10 + a %10;
a /=10;
}
将新数整体左移一位,然后 取每个数的第i位置,将该位放到 新数的最低位。循环32次遍可以得到翻转。
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for(int i = 0 ; i < 32;i++){
res = (res<<1) | ((n>>>i)&1);
}
return res;
}
}
减少 n的 位移数
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for(int i = 0 ; i < 32;i++){
res = (res<<1) | (n&1);
n=n>>>1;
}
return res;
}
}