Skip to content

Latest commit

 

History

History
51 lines (47 loc) · 1.1 KB

190. Reverse Bits.md

File metadata and controls

51 lines (47 loc) · 1.1 KB

题目

190. Reverse Bits

思路

4ms 83.12%

用queue存储每位然后吐出即可,还是得用位运算才行。

改进,4ms 83.12&

不需要queue,直接每步循环内即可完成

8ms 55.48% bitset库。 将整数放入bitset中,遍历即可。但性能没有想象中的好,大概底层运算还是与或非,移位快一点吧。

代码

思路一

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        queue<int> s;int k=32;
        uint32_t result=0;
        while(k-->0){
            int m=n&0x00000001;
            s.push(m);
            n=n>>1;
        }
        while(!s.empty()){
            result=result<<1;
            result+=s.front();
            s.pop();
        }
        return result;
    }
};

思路二

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        bitset<32> b(n);
        for(int i=0;i<16;i++){
            if(b[i]!=b[31-i]){
                b[i]=!b[i];
                b[31-i]=!b[31-i];
            }
        }
        
        return b.to_ulong();
    }
};