191. Number of 1 Bits

Solution

int hammingWeight(uint32_t n) {
    uint32_t result = 0;
    
    while(n > 0) {
        result += n % 2;
        n = n >> 1;
    }
    
    return result;
}
int hammingWeight(uint32_t n) {
    uint32_t result = 0;
    
    while(n > 0) {
        n = n & (n - 1);
        result++;
    }
    
    return result;
}

Complexity

  • Time Complexity: O(32), or O(1), since the number of bits in an unsigned integer are constant. The second solution is O(N), where N is the number of 1s in n.
  • Space Complexity: O(1).

All Solutions