[Leetcode] [Java] [JavaScript] Counting Bits

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.