返回介绍

solution / 0300-0399 / 0338.Counting Bits / README_EN

发布于 2024-06-17 01:04:01 字数 4063 浏览 0 评论 0 收藏 0

338. Counting Bits

中文文档

Description

Given an integer n, return _an array _ans_ of length _n + 1_ such that for each _i_ _(0 <= i <= n)_, _ans[i]_ is the number of _1_'s in the binary representation of _i.

 

Example 1:

Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2:

Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

 

Constraints:

  • 0 <= n <= 105

 

Follow up:

  • It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?
  • Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?

Solutions

Solution 1

class Solution:
  def countBits(self, n: int) -> List[int]:
    return [i.bit_count() for i in range(n + 1)]
class Solution {
  public int[] countBits(int n) {
    int[] ans = new int[n + 1];
    for (int i = 0; i <= n; ++i) {
      ans[i] = Integer.bitCount(i);
    }
    return ans;
  }
}
class Solution {
public:
  vector<int> countBits(int n) {
    vector<int> ans(n + 1);
    for (int i = 0; i <= n; ++i) {
      ans[i] = __builtin_popcount(i);
    }
    return ans;
  }
};
func countBits(n int) []int {
  ans := make([]int, n+1)
  for i := 0; i <= n; i++ {
    ans[i] = bits.OnesCount(uint(i))
  }
  return ans
}
function countBits(n: number): number[] {
  const ans: number[] = Array(n + 1).fill(0);
  for (let i = 0; i <= n; ++i) {
    ans[i] = bitCount(i);
  }
  return ans;
}

function bitCount(n: number): number {
  let count = 0;
  while (n) {
    n &= n - 1;
    ++count;
  }
  return count;
}

Solution 2

class Solution:
  def countBits(self, n: int) -> List[int]:
    ans = [0] * (n + 1)
    for i in range(1, n + 1):
      ans[i] = ans[i & (i - 1)] + 1
    return ans
class Solution {
  public int[] countBits(int n) {
    int[] ans = new int[n + 1];
    for (int i = 1; i <= n; ++i) {
      ans[i] = ans[i & (i - 1)] + 1;
    }
    return ans;
  }
}
class Solution {
public:
  vector<int> countBits(int n) {
    vector<int> ans(n + 1);
    for (int i = 1; i <= n; ++i) {
      ans[i] = ans[i & (i - 1)] + 1;
    }
    return ans;
  }
};
func countBits(n int) []int {
  ans := make([]int, n+1)
  for i := 1; i <= n; i++ {
    ans[i] = ans[i&(i-1)] + 1
  }
  return ans
}
function countBits(n: number): number[] {
  const ans: number[] = Array(n + 1).fill(0);
  for (let i = 1; i <= n; ++i) {
    ans[i] = ans[i & (i - 1)] + 1;
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文