Very neat C++ Solution


  • 9
    Z
    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            for (int i = 0; i < 16; i++)
                // toggle bits when the 2 bits in a pair are different
                if ((n >> i & 1) ^ (n >> (31 - i) & 1))
                    n ^= (1 << i | 1 << (31 - i));
            return n;
        }
    };

  • 0
    Q

    // same idea.

    uint32_t reverseBits(uint32_t n) {
    	for(uint32_t low=1, high=1<<31;low<high;low<<=1,high>>=1) {
    		if((int)((bool)(n&low))^(int)((bool)(n&high))) { n^=(low|high); }
    	}
    	return n;
    }

  • 0
    P
    This post is deleted!

Log in to reply
 

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