Leetcode--Counting Bits

Source: Internet
Author: User

Question:

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 the using any builtin function like __builtin_popcount in C + + or any other language.

    Analysis:

    Given a nonnegative integer, num, for each I of 0≤i≤num, calculates how many of the bits in I are 1, and returns an array of the number of records 1.

    Follow up:

    Can you just walk through the time in O (n) to get an answer?

    The spatial complexity is O (n).

    Ideas:

    Because the number of 1 is calculated, it must be related to the remainder after 2 and 2. The calculation is incremented, so the next number can take advantage of the result of the previous number.

    The code is as follows:

     Public classSolution { Public int[] Countbits (intnum) {        int[] DP =New int[Num+1]; dp[0] = 0;  for(intI=1; i<=num; i++) {            intT1 = I/2; intt2 = i% 2; Dp[i]= Dp[t1] +T2; }        returnDP; }}

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