The beauty of programming Reading Notes -- "calculate the number of 1 in the binary number"

Source: Internet
Author: User
Tags integer division

"The beauty of programming -- Microsoft technology interview experiences"

"Calculate the number of 1 in the binary number"

By zellux

 

By the Electronic Industry Press Bowen viewpoint and w3china.org community jointly held a "look at the chapter, write book reviews, win the" Beauty of programming-Microsoft technology interview experience "activities, see: http://bbs.w3china.org/dispbbs.asp? Boardid = 42 & id = 61162

Everyone was enthusiastic about the event. The following article is from Reader zellux:

Calculates the number of 1 in binary. For an 8-bit variable, the binary representation of the number of "1" requires the algorithm to be executed as efficiently as possible.

Let's take a look at several algorithms in the sample chapter:

Solution 1: divide the number by two each time to see if it is an odd number. If it is yes, the sum is incremented. The final result is the number of 1 in the binary representation.

Solution 2: A loop is also used, but the operation in the loop is simplified by the displacement operation.

1: int count (int v)
2 :{
3: int num = 0;
4: While (v ){
5: num + = V & 0x01;
6: V> = 1;
7 :}
8: Return num;
9 :}

Solution 3: Use a clever operation. V & (V-1) can eliminate the last digit 1 in the binary representation each time. This technique can reduce the number of cycles.

Solution 4: look-up table method. Because there is only 8 bit data, you can directly create a table that contains the number of 1 in each number, and then look up the table. Complexity O (1 ).

1: int counttable [256] = {0, 1, 1, 2, 1,..., 7, 7, 8 };
2:
3: int count (INT v ){
4: Return counttable [v];
5 :}

Well, this is the four solutions provided in the chapter. Let's talk about my views.

The first is to measure the algorithm. Is complexity really the only criterion? Complexity is a secondary factor, especially when the data size is given and small.

The complexity of the look-up table method is O (1). I use solution 1. The cycle is fixed eight times, and the complexity is also O (1 ). As the data grows and becomes a 32-bit integer, The lookup method is naturally not suitable.

Secondly, I think that since it is such a small operation, the measurement scale must be small, and the CPU clock cycle can be used as a reference.

Solution 1 involves several integer addition, several integer division (the General compiler can optimize it to shift), several cycle branch judgments, and several parity judgments (this is time-consuming, according to the data on the csapp, a branch penalty usually consumes about 14 cycle S.) add up to dozens of cycle S.

Let's look at solution 4 again. The look-up table method seems to be able to solve the problem with an address calculation, but in fact an access operation is used here, and it is very likely that the array is not in the cache during the first access, the consequence of such a cache miss may be that it consumes dozens or even hundreds of cycle instances (because it needs to access the memory ). Therefore, for such "small operations", the performance of this algorithm is actually very poor.

Here I recommend several algorithms to solve this problem, taking a 32-bit unsigned integer as an example.

1: int count (unsigned X ){
2: x = x-(x> 1) & 0x55555555 );
3: x = (X & 0x33333333) + (x> 2) & 0x33333333 );
4: x = (x + (x> 4) & 0x0f0f0f;
5: x = x + (x> 8 );
6: x = x + (x> 16 );
7: Return X & 0x0000003f;
8 :}

Here we use the bipartite method. We add two groups, and then add four groups, and then we get the sum of eight groups.

A more clever hakmem Algorithm

1: int count (unsigned X ){
2: Unsigned N;
3:
4: N = (x> 1) & 033333333333;
5: x = x-N;
6: N = (n> 1) & 033333333333;
7: x = x-N;
8: x = (x + (x> 3) & 030707070707;
9: x = modu (x, 63 );
10: Return X;
11 :}

First, we need to calculate the number of one in each of the three binary groups, and then merge the two adjacent groups to obtain the number of one in each of the six groups, in the end, the results are obtained with the exception of 63.

Because 2 ^ 6 = 64, that is, x_0 + X_1 * 64 + x_2 * 64*64 = x_0 + x_1 + x_2 (mod 63), the equal signs here represent the same remainder.

This program only requires about 10 commands, and does not access the memory, the speed is very fast.

It can be seen that the actual performance of an algorithm depends not only on complexity, but also on other situations.

The first question about the next two extensions is how to handle the 32-bit integer.

Question 2: Given two integers A and B, ask a and B how many bits are different.

This problem is actually an extra step for the number 1 problem. You only need to calculate the variance or result of A and B, and then calculate the number of 1 in this value.

In general, this book is quite good. I like the style that puts forward different algorithms for a problem and keeps improving. I would like to give you a personal understanding here ;-)

 

Recommended topics:

The beauty of programming Reading Notes (2): Sorting of a pile of pancakes

Reading Notes of the beauty of programming (I): Question about Chinese chess masters

Sun Tzu's Art of War by database developers

Authoritative PHP 5 Programming-amazing changes

New-generation interface programming experience

Horizontal evaluation: one book, two people

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.