C solution, bit operation


  • 0
    C
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            n = ((n >> 1) & 0x55555555) + (n & 0x55555555);
            n = ((n >> 2) & 0x33333333) + (n & 0x33333333);
            n = ((n >> 4) & 0x0f0f0f0f) + (n & 0x0f0f0f0f);        
            n = ((n >> 8) & 0x00ff00ff) + (n & 0x00ff00ff);
            n = ((n >> 16) & 0xffff) + (n & 0xffff);
            return n;
        }
    };

Log in to reply
 

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