Reverse Bits

Reverse Bits

Total Accepted: 45982 Total Submissions: 157761 Difficulty: Easy

 

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

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        bitset<32> bits(n);
        int i=0,j=31;
        while(i<j){
            int d = bits[i];
            bits[i] = bits[j];
            bits[j] = d;
            i++;
            j--;
        }
        return  bits.to_ulong();
    }
};

 

posted @ 2015-12-16 20:53  zengzy  阅读(128)  评论(0编辑  收藏  举报
levels of contents