Skip to content

191. Number of 1 Bits 👍

Approach 1: Naive

  • Time: $O(32) = O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int hammingWeight(uint32_t n) {
    int ans = 0;

    for (int i = 0; i < 32; ++i)
      if ((n >> i) & 1)
        ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Solution {
  // you need to treat n as an unsigned value
  public int hammingWeight(int n) {
    int ans = 0;

    for (int i = 0; i < 32; ++i)
      if (((n >> i) & 1) == 1)
        ++ans;

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def hammingWeight(self, n: int) -> int:
    ans = 0

    for i in range(32):
      if (n >> i) & 1:
        ans += 1

    return ans

Approach 2: Built-in

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  int hammingWeight(uint32_t n) {
    return __builtin_popcount(n);
  }
};
1
2
3
4
5
6
public class Solution {
  // you need to treat n as an unsigned value
  public int hammingWeight(int n) {
    return Integer.bitCount(n);
  }
}
1
2
3
class Solution:
  def hammingWeight(self, n: int) -> int:
    return bin(n).count('1')