C++ solution with bitset


  • 3
    D
    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            const int size = 32;
            bitset<size> bSet(n);
            for(int i=0; i < size/2; i++){
                int temp = bSet[i];
                bSet[i] = bSet[size - i - 1];
                bSet[size - i -1] = temp;
            }
            return (uint32_t) bSet.to_ulong();
        }
    };
    

    I am using bitset.

    1. construct bitset from uint32_t
    2. use to_ulong to convert bitset to ulong then casting to uint32_t.

  • 0
    H

    I'm using bitset as well as std::string, std::reverse - how to determine which level of "hand-making" should be achieved?

    uint32_t reverseBits(uint32_t n) { //10-12ms
       bitset<32> bits(n);
       string s = bits.to_string();
       std::reverse(s.begin(), s.end());
       return bitset<32>(s).to_ulong();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.