Bit operation solution(C++) O(1)


  • 3
    C
    int hammingWeight(uint32_t n) 
    {
        uint32_t mask = 0x55555555;
        uint32_t cnt = ((n>>1)&mask) + (n&mask);
        
        mask = 0x33333333;
        cnt = ((cnt>>2)&mask) + (cnt&mask);
        
        mask = 0x0F0F0F0F;
        cnt = ((cnt>>4)&mask) + (cnt&mask);
        
        mask = 0x00FF00FF;
        cnt = ((cnt>>8)&mask) + (cnt&mask);
        
        mask = 0x0000FFFF;
        cnt = ((cnt>>16)&mask) + (cnt&mask);
        
        return cnt;
    }

Log in to reply
 

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