Leetcode 338. Counting Bits

Source: Internet
Author: User

338. 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
  • classSolution { Public: Vector<int> Countbits (intnum) {Vector<int> Count_v (num+1,0);  for(inti =1; I <= num;i++)        {            intx =i; intCount=0;  while(x) {if((X &1)==1) count++; X>>=1; } Count_v[i]=count; }        returnCount_v; }};

    Note: 1. Calculate the number of 1 in binary, the difficulty lies in the complexity of time. There are three basic ways to find binary 1 numbers:

  • (1) theorem solving: The method of taking the remainder, the slowest.
  • (2) Basic Law (FOG): Values and 1 for & operations, then >> arithmetic right shift, there are still two loops. (That is, my solution to this problem)
  • (3) Fast method: N and n-1 for & operation, can eliminate the binary right 1, there are still two loops. (Solution in 191 questions)
  • Reference: http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

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