题目

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 1:

  1. Input: 2
  2. Output: [0,1,1]

Example 2:

  1. Input: 5
  2. Output: [0,1,1,2,1,2]

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

题意

计算整数0-num的每一个数的二进制中的1的个数。要求时间复杂度为0338. Counting Bits (M) - 图1,而非0338. Counting Bits (M) - 图2

思路

个人的做法是针对每一个整数num,它二进制中1的个数,就等于把它最高位的1去掉后得到的整数的二进制中1的个数加1,如8的二进制为1000,而去掉最高位1得到的整数为0,所以8的二进制中1的个数为0+1=1。

更巧妙的方法是对于每个整数i,i&(i-1)的结果就相当于把i最右边的1变为0,这样很容易得到count[i] = count[i&(i-1)] + 1。


代码实现

Java

去掉最高位

  1. class Solution {
  2. public int[] countBits(int num) {
  3. int[] count = new int[num + 1];
  4. count[0] = 0;
  5. int size = 1;
  6. int cnt = 0;
  7. for (int i = 1; i <= num; i++) {
  8. if (cnt == size) {
  9. cnt = 0;
  10. size *= 2;
  11. }
  12. count[i] = count[i - size] + 1;
  13. cnt++;
  14. }
  15. return count;
  16. }
  17. }

去掉最右1

  1. class Solution {
  2. public int[] countBits(int num) {
  3. int[] count = new int[num + 1];
  4. count[0] = 0;
  5. for (int i = 1; i <= num; i++) {
  6. count[i] = count[i & (i - 1)] + 1;
  7. }
  8. return count;
  9. }
  10. }