颠倒给定的 32 位无符号整数的二进制位。
示例 1:
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
示例 2:
输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
思路
使用位运算可以缩短运行时间
x%2 == 1 ——>(x&1) == 1
x%2 == 0 ——>(x&1) == 0
x = x*2; ——> x = x<<1;
x = x/2; ——> x = x>>1;
方法1:
uint32_t reverseBits(uint32_t n) {
uint32_t a = 0;
for(int i = 0; i < 32; i++) {
a = a * 2 + n % 2;
n = n / 2;
}
return a;
}
方法2:
uint32_t reverseBits(uint32_t n) {
uint32_t a = 0;
for(int i = 0; i < 32; i++) {
a = (a << 1) + (n & 1);
n = n >> 1;
}
return a;
}