[LeetCode][Java][JavaScript]Counting Bits

Counting Bits

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].

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

https://leetcode.com/problems/counting-bits/


计算转成二进制之后有几个1。

动态规划,二进制每多一位就把结果数组中所有的结果都加一,再放回结果数组中。

Java:

 1 public class Solution {
 2      public static int[] countBits(int num) {
 3         if(num == 0) return new int[]{0};
 4         int[] result = new int[num + 1];
 5         int len, count = 0;
 6         while(true){
 7             len = count + 1;
 8             for(int i = 0; i < len; i++){
 9                 count++;
10                 result[count] = result[i] + 1;                
11                 if(count >= num)
12                     return result;
13             }
14         }
15     }
16 }

Javascript:

 1 /**
 2  * @param {number} num
 3  * @return {number[]}
 4  */
 5 var countBits = function(num) {
 6     if(num === 0) return [0];
 7     var result = [0], len, count = 0;
 8     while(true){
 9         len = result.length;
10         for(var i = 0; i < len; i++){
11             result.push(result[i] + 1);
12             count++;
13             if(count >= num)
14                 return result;
15         }
16     }
17 };
原文地址:https://www.cnblogs.com/Liok3187/p/5296180.html