[Beauty of programming] 2.1 calculate the number of 1 in binary

Source: Internet
Author: User
Question: For an unsigned integer variable in a byte, the binary value indicates the number of 1 in the variable, and the algorithm execution efficiency must be as efficient as possible. Question Analysis: This question also appears in the number of 1 in the "Sword refers to offer" interview question 10: binary, but the unsigned number is not mentioned in the "Sword refers to offer" interview question 10, therefore, consider one more level than this question. The following is a summary

Question: For an unsigned integer variable in a byte, the binary value indicates the number of 1 in the variable, and the algorithm execution efficiency must be as efficient as possible. Question Analysis: This question also appears in the number of 1 in the "Sword refers to offer" interview question 10: binary, but the unsigned number is not mentioned in the "Sword refers to offer" interview question 10, therefore, consider one more level than this question. The following is a summary


Question:

For a byte unsigned integer variable, the binary value indicates the number of 1 in the variable, which requires the algorithm to be executed as efficiently as possible.


Question Analysis:

This question also appears in question 10: Number of 1 in the binary system, but the unsigned number is not mentioned in question 10, therefore, consider one more level than this question. Below are several solutions to this question.


Solution 1 (used for this question ):

We usually think that dividing by 2 is to shift the binary value to the right, but to judge whether the removed value is 0 or 1, we need to take the remainder of 2. The idea is simple. You can use four arithmetic operations to answer the following questions:

int Count(Byte v){    int num = 0;    while(v){        if(v%2)            num++;        v /= 2;    }    return num;}

Solution 2 (for this question ):

For binary shifts to the right by dividing by 2, Division is much less efficient than direct shift. If you encounter such a problem, try to use shift instead. Bitwise operations take five forms: with, or, XOR, left shift, and right shift. Find the operation you want in these ranges. When the shift is performed, you must determine whether the removed value is 0 or 1. Here, you should use the operation to determine whether the last bit is 1.

Int Count2 (Byte v) {int num = 0; while (v) {if (v & 1) num ++; // you can also use num + = v & 1; to replace the preceding two rows v = v> 1;} return num ;}

Solution 3 ):

If this question is signed, when the right shift is performed, the symbol bit will be added at a high position. If the above two methods are used, the question will go into an endless loop. How to avoid it? You can first determine the highest bit, and then traverse n-1 times to determine whether the bit except the highest bit is 1. This method is troublesome. We can change our thinking by constantly shifting the given 1 to the left until we move 1 to the highest bit.

int Count3(Byte v){    int num = 0;    int flag = 1;    while(flag){        if(v & flag)            ++num;        flag = flag << 1;    }    return num;}

Solution 4 (more efficient algorithms ):

This method makes full use of Binary-related operations and usually collects such operations.

If the number is not 0, the binary value must contain 1. When this number is subtracted from 1, the value of 1 in the first digit ranges from 1 to> 0, and the value of 0 in the lower position ranges from 0 to> 1. When the phase between n and N-1 is given, the value of 1 in n is 0. If one such operation deletes 1, then the number of 1 in the binary can be exactly repeated.

int Count4(Byte v){    int num = 0;    while(v){        ++num;        v = v & (v-1);    }    return num;}


Solution 5 (Spatial time change method ):

In fact, Method 4 is good enough, but because it only involves eight digits, we can choose to directly select the corresponding data. For example, 0x1-0x2-0x4... all contain 1; 0x3-0x6... contains 2 1; and so on. Select the result using the switch statement. However, this method may be less efficient, because when the input v is 255, the corresponding data can be found only after comparison.

int Count5(Byte v){    int num = 0;    switch(v){    case 0x0:        num = 0;        break;    case 0x1:    case 0x2:        ....    }    return num;}

Solution 6 (hash table method ):

Now that we think of using space for time, we simply use an array to represent the number of indexes to be searched, and counttable [index] indicates the number of 1 contained in the data.







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.