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

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


class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        //不用位操作也能完成,只是效率不高
        // uint32_t result = 0;
        // for(int i=31;i>=0;i--){
        //     result += n%2*pow(2,i);
        //     n = n/2;
        // }
        // return result;
        
        uint32_t m=0;
        for(int i=0;i<32;i++){
            m<<=1;
            m = m|(n & 1);
            n>>=1;
        }
        return m;
        
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章