AdSense

Monday, March 9, 2015

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).


I am still not good at bits operation. Even though now I can solve the problem by myself, it still takes certain time manner.


public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        if(n == 0)
            return n;
        int rst = 0;
        for (int b = 31; b >= 0; b--){
            rst |= ((n & 1) << b);
            n = n >> 1;
        }
        return rst;
    }
}

No comments:

Post a Comment