Skip to content

338. Counting Bits 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  vector<int> countBits(int n) {
    // let f(i) := i's # of 1's in bitmask
    // f(i) = f(i / 2) + i % 2
    vector<int> ans(n + 1);

    for (int i = 1; i <= n; ++i)
      ans[i] = ans[i / 2] + (i & 1);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int[] countBits(int n) {
    // let f(i) := i's # of 1's in bitmask
    // f(i) = f(i / 2) + i % 2
    int[] ans = new int[n + 1];

    for (int i = 1; i <= n; ++i)
      ans[i] = ans[i / 2] + (i % 2 == 0 ? 0 : 1);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def countBits(self, n: int) -> List[int]:
    # let f(i) := i's # of 1's in bitmask
    # f(i) = f(i / 2) + i % 2
    ans = [0] * (n + 1)

    for i in range(1, n + 1):
      ans[i] = ans[i // 2] + (i & 1)

    return ans