您的位置:首页 > 其它

Reverse Bits

2016-07-12 14:38 357 查看
Reverse bits of a given 32 bits unsigned integer.

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

Follow up:

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

JAVA解法:

解法1:32位的整数,从最低位与最高位开始分别观察,若对应位置上异或为1,则需交换两者的位置。否则不交换;

解法2: 32位的整数,从最低位开始遍历,每位向左移位(32-i-1)位。

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;
if((n == 0) || (n == 0xffffffff ))
{
return n;
}
for(int k = 0; k < 32; k++)
{
if((n & 0x01) == 1)
{
result |= (1 << (32-k-1));
}
n = n>>1;
}
return result;
}
}


int Int_Size = Integer.SIZE;
if((n == 0) || (n == 0xffffffff ))
{
return n;
}
for(int i = 0; i <  Int_Size/2; i++)
{
int j = Int_Size-1-i;

int low = (n >> i) & 1;
int high = (n >> j) & 1;

int a = 1 << i;
int b = 1 << j;
if((low ^ high) == 1)
{
n = n ^ (a|b);
}

}
return n;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  位运算