"Leetcode" Counting Bits

Source: Internet
Author: User

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

Topic:

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 retur n 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.
Ideas:C[i]: How many 1 state transition equations are in the binary of number I:c[i]=c[i>>1]+i&1For example, the binary 111 of the number 7 only needs to calculate the number of the last and the first two digits of 1, and the number of the first two bits and 110 is the same, and 11 is the same.

Algorithm:

Public int[] countbits (int num) {      int res[] = new int[num+1];      for (int i=0;i<=num;i++) {          Res[i] = res[i>>1]+ (i&1);      }      return res;  }  


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