颠倒给定的 32 位无符号整数的二进制位。
示例 1:
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ret = 0;
for(int count = 0; count < 32; count ++){
if(n < 0) //对于有符号数,最高位为1说明是个负数,因此可以把1提提出来,放在目标数的尾部1<<count(2的count次方)的位置。
ret += (1 << count);
n = n << 1;
}
return ret;
}
}
浙公网安备 33010602011771号