定个小目标之刷LeetCode热题(41)

338. 比特位计数

给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。

今天看一下这道简单题,主要考查位运算,代码如下

class Solution {
    public int[] countBits(int n) {
        int[] bits = new int[n + 1];
        int heightBit = 0;
        for (int i = 1; i <= n; i++) {
            if ((i & (i - 1)) == 0) {
                heightBit = i;
            }
            bits[i] = bits[i - heightBit] + 1;
        }
        return bits;
    }
}

题目链接:题单 - 力扣(LeetCode)全球极客挚爱的技术成长平台

相关推荐

  1. 目标LeetCode41

    2024-07-11 20:30:04       19 阅读
  2. 目标LeetCode43

    2024-07-11 20:30:04       20 阅读
  3. 目标LeetCode45

    2024-07-11 20:30:04       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 20:30:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 20:30:04       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 20:30:04       58 阅读
  4. Python语言-面向对象

    2024-07-11 20:30:04       69 阅读

热门阅读

  1. 详细介绍一下TypeScript

    2024-07-11 20:30:04       23 阅读
  2. Ant-Vue——modal对话框

    2024-07-11 20:30:04       23 阅读
  3. windows 修改 npmrc

    2024-07-11 20:30:04       22 阅读
  4. Python图形用户界面的文本文件加密工具

    2024-07-11 20:30:04       26 阅读
  5. [QT入门]树形视图控件

    2024-07-11 20:30:04       22 阅读
  6. Redis事件和整体框架

    2024-07-11 20:30:04       21 阅读
  7. House holder reflections and Givens rotations

    2024-07-11 20:30:04       20 阅读
  8. Python开发 ——循环中的 `continue` 语句

    2024-07-11 20:30:04       21 阅读
  9. Spring的bean的生命周期——bean的创建与销毁

    2024-07-11 20:30:04       21 阅读