9ms C++ code using union and array mapping


  • 0
    F

    Tried to use union to avoid loop from beginning bit to end bit, also used existing array to get the reversed bits in half-byte.

      uint32_t reverseBits(uint32_t n) {
            int map[16]={0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};
            union{
                uint32_t m;
                struct{
                    char ab;
                    char cd;
                    char ef;
                    char gh;
                }sn;
            }un;
            un.m=n;
            char temp=un.sn.ab;
            un.sn.ab=map[un.sn.gh&0x0F]<<4|map[(un.sn.gh>>4)&0x0F];
            un.sn.gh=map[temp&0x0F]<<4|map[(temp>>4)&0x0F];
            temp=un.sn.cd;
            un.sn.cd=map[(un.sn.ef&0x0F)]<<4|map[(un.sn.ef>>4)&0x0F];
            un.sn.ef=map[temp&0x0F]<<4|map[(temp>>4)&0x0F];
            return un.m;
        }`enter code here`

Log in to reply
 

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