[LeetCode 190]Reverse Bits

来源:互联网 发布:java程序开发培训价格 编辑:程序博客网 时间:2024/06/17 03:43

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?

public int reverseBits(int n) {        int[] bits = new int[32];        Arrays.fill(bits, 0);        int num = 0;        if(n<0){            bits[31] = 1;            n = n^ Integer.MIN_VALUE;        }        for(int i=0;i<bits.length-1;i++){            bits[i] = n%2;            n /=2;        }        for(int i=1;i<bits.length;i++){            num<<=1;            num+=bits[i];        }        return (bits[0]==1)? num|Integer.MIN_VALUE:num;     }




0 0