【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 的数目并将它们作为数组返回。
61 0
LeetCode 338. Counting Bits
LeetCode 190. Reverse Bits
颠倒给定的 32 位无符号整数的二进制位。
72 0
LeetCode 190. Reverse Bits
|
C++
Leetcode-Medium 338. Counting Bits
Leetcode-Medium 338. Counting Bits
82 0
LeetCode 191 Number of 1 Bits(1 比特的数字们)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50506429 翻译 写一个函数获取一个无符号整型数,并且返回它的“1”比特的数目(也被叫做Hamming weight)。
972 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).
988 0
|
23天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题