Three kinds of bit manipulation solutions C++


  • 0
    X

    First solution:

       class Solution {
        public:
            uint32_t reverseBits(uint32_t n) {
                uint32_t res=UINT_MAX;
                for(int i=0; i <= 31; i++) {
                    uint32_t curBit = (n >> i) & 0x01;
                    if(curBit)
                        res |= 1 << (31-i); //set 1
                    else
                        res &= ~( 1 << (31-i) ); //set 0
                }
                return res;
            }
        };
    

    Second solution, using xor

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            uint32_t res=0x0;
            for(int i=0; i <= 31; i++) {
                uint32_t curBit = (n >> i) & 0x01;
                res ^= curBit << (31-i);
            }
            return res;
        }
    };
    

    Third solution, using or:

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            uint32_t res=0;
            for(int i=0; i <= 31; i++) {
                uint32_t curBit = (n >> i) & 0x01;
                res |= ( curBit << (31-i) );
            }
            return res;
        }
    };

Log in to reply
 

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