Reverse Bits

来源:互联网 发布:linux 关闭ntpdate 编辑:程序博客网 时间:2024/05/29 09:24

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;    }}
0 0