Two solutions in c++, results surprised me


  • 0
    O

    I implement in two ways, the ideas are simple, almost the same as others. However, the first one runs 1ms faster than second one, which suprised me.

    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
    	uint32_t ans = 0;
    	int bit = 0;
    	int i = 0;
    	while(i++ < 32)
    	{
    		bit = n % 2;
    		ans = ((ans << 1) + bit);
    		n = n >> 1;
    	}
    	return ans;
        }
    };
    
    
    class Solution {
    public:
    uint32_t reverseBits(uint32_t n){
    	uint32_t ans = 0;
    	for(int i = 0; i < 32; i++)
    	{
    	    ans <<= 1;
    		ans |= (n & 1);
    		n >>= 1;
    	}
    	return ans;
    }
    };

Log in to reply
 

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