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 you num = 5 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 I do it in linear time O (n)/possibly in a single pass?
- Space complexity should be O (n).
- Can 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/
After the calculation is turned into binary there are several 1.
Dynamic planning, binary each one adds one to the result array, and then puts it back in the result array.
Java:
public class Solution {public static int[] countbits (int num) { if (num = = 0) return new int[]{0}; Int[] result = new Int[num + 1]; int len, count = 0; while (true) { len = count + 1; for (int i = 0; i < len; i++) { count++; Result[count] = Result[i] + 1; if (Count >= num) return result;}}}}
Javascript, like Java code, Force MLE, wait a few days to see if the bug can be fixed:
/** * @param {number} num * @return {number[]} */var countbits = function (num) {if (num = = 0) return [0]; var result = [0], len, count = 0; while (true) { len = result.length; for (var i = 0; i < len; i++) { Result.push (Result[i] + 1); count++; if (Count >= num) return result;}} ;
[Leetcode] [Java] [JavaScript] Counting Bits