optimization of number of digits 1 in statistical binary expansion

Source: Internet
Author: User

Problem:

For any nonnegative integer, the total number of bits 1 is counted in the binary expansion.

Solve:

Related blog:http://www.cnblogs.com/maples7/p/4324844.html

Before reading this article, we can look at the above article, this article mainly discusses its optimization problem.

General Solution:

O (LOGN):

1 intCountones (unsignedintN)2 {3     intones =0;4      while(0<N)5     {6Ones + = (1&n);7N >>=1;8     }9     returnones;Ten}

It's just that every time you take the second binary, the last one is 1 counts.

The efficiency is known by bit operations (the right shift is equivalent to dividing by 2), which is O (LOGN).

Optimization Solution 1:

O (Countones (n)):

1 intCountOnes1 (unsignedintN)2 {3     intones =0;4      while(0<N)5     {6ones++;//count (last at least one is 1)7N &= N-1;//clear the right 1 at the moment.8     }9     returnones;Ten}

The explanations are as follows:

Optimization Solution 2:

O (LOGW), W = O (logn) is the bit width of an integer, which is actually an O (1) algorithm .

Code and Explanation:

This algorithm is a strategy for merging counters. The 32Bit of the input counts as 32 counters, representing 1 numbers per bit. Then merge the adjacent 2 "counter", make I become 16 counters, each counter value is the number of 2 bit 1, continue to merge adjacent 2 "counter", so I becomes 8 counters, each counter value is 4 bit 1 number. And so on, until I becomes a counter, its value is the number of bits in the value of 1 in the I of 32Bit.

From: "Data structure exercises analysis", Deng Junhui

Reference:

1, http://blog.chinaunix.net/uid-21275705-id-224360.html

2, Http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

optimization of number of digits 1 in statistical binary expansion

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.