您的位置:首页 > 其它

LeetCode 190. Reverse Bits(翻转比特)

2016-05-04 02:49 330 查看
原题网址:https://leetcode.com/problems/reverse-bits/

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:

If this function is called many times, how would you optimize it?

Related problem: Reverse Integer
方法一:直接操作。

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int reversed = 0;
for(int i=0; i<32; i++) {
reversed <<= 1;
reversed |= n & 1;
n >>= 1;
}
return reversed;
}
}


方法二:参考:https://leetcode.com/discuss/27405/o-1-bit-operation-c-solution-8ms

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int s = n >= 0 ? 0 : 1;
n &= 0b01111111111111111111111111111111;
long m = n;
m = ((m & 0xffff0000) >> 16) | ((m & 0x0000ffff) << 16);
m = ((m & 0xff00ff00) >> 8) | ((m & 0x00ff00ff) << 8);
m = ((m & 0xf0f0f0f0) >> 4) | ((m & 0x0f0f0f0f) << 4);
m = ((m & 0xcccccccc) >> 2) | ((m & 0x33333333) << 2);
m = ((m & 0xaaaaaaaa) >> 1) | ((m & 0x55555555) << 1);
m |= s;
return (int)m;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: