【LeetCode】Counting Bits(338)

简介:   Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

1. Description


  Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.


  Example:


  For num = 5 you should return [0,1,1,2,1,2].


2. Answer 


public class Solution {
    public int[] countBits(int num) {
        int[] result = new int[num + 1];
        for (int i = 1; i <= num; i++) {
            result[i] = result[i & (i - 1)] + 1;
        }
        return result;
    }
}
目录
相关文章
|
算法 C++
LeetCode 338. Counting Bits
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
75 0
LeetCode 338. Counting Bits
LeetCode 190. Reverse Bits
颠倒给定的 32 位无符号整数的二进制位。
92 0
LeetCode 190. Reverse Bits
|
C++
Leetcode-Medium 338. Counting Bits
Leetcode-Medium 338. Counting Bits
96 0
LeetCode 191 Number of 1 Bits(1 比特的数字们)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50506429 翻译 写一个函数获取一个无符号整型数,并且返回它的“1”比特的数目(也被叫做Hamming weight)。
1000 0
LeetCode 191 Number of 1 Bits
题目描述: Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
1010 0
|
3月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行