比特位计数

题目描述:给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:库函数

偷懒的我直接用了java的库函数Integer.bitCount解决了这道题。 自我鄙视一下

提示:可以用动态规划实现更高效的解法。

  1. public class LeetCode_338 {
  2. /**
  3. * 使用库函数 Integer.bitCount 直接获取整数对应的二进制的1的个数
  4. *
  5. * @param n
  6. * @return
  7. */
  8. public static int[] countBits(int n) {
  9. int[] result = new int[n + 1];
  10. for (int i = 0; i <= n; i++) {
  11. result[i] = Integer.bitCount(i);
  12. }
  13. return result;
  14. }
  15. public static void main(String[] args) {
  16. for (int i : countBits(100)) {
  17. System.out.println(i);
  18. }
  19. }
  20. }

【每日寄语】 很多时候,颠倒一下视角,会发现一个全新的世界。