Number of "1" in the statistical binary number (understand binary)

Source: Internet
Author: User
Tags bitwise

problem Description: There are 10 kinds of people in the world, one understands the binary system, one does not understand. So you know the binary expression of two int32 integers m and n, how many bits are different?

function Prototypes: int countbitdiff (int m, int n)

Input:

1999 2299

Output:

7

Analysis: This topic from the 2016 Millet online pen test, to compare the bits of M and N, you can use the additional variable v and different or operation to achieve, the practice is:

V=m^n;

The number of binary 1 in binary representations of V after XOR or operation is that of the different bits of M and N, and the problem is converted to the number of binary number 1 in a binary number v.

Solution One: bitwise comparison

The easiest way to think of this is to compare the binary values of each bit in V to 1, using the shift operator in C and pointers to achieve this comparison:

/**
 * Obtains two integer binary expression digits of different number
 * @param m int m
 * @param n integer n
 * @return integral
/int Countbitdiff (int m, int n) {
    unsigned int c = m ^ n; 
    char ones;
    for (ones = 0; c!= 0; c >>= 1) {
        if ((C & 1)!= 0)
            ones + = 1;
    }
    return ones;
}

solution Two: With the help of n& (n-1)

The second method is special, using a special property of bitwise and special, namely:

Suppose the binary value of the binary number n has a k bit is 1,
Then the n& (n-1) binary value of 1 digits is k-1.

Using the special properties of n& (n-1), you can write the following code:

/**
 * Obtains two different number of shaping binary expression numbers
 * @param m integer m
 * @param n integer n
 * @return integral
/int Countbitdiff (int m, int N) {
    int c = m ^ n;//Bitwise XOR or
    char counter = 0;
    for (; c; ++counter) c &= (c-1);
    return counter;
}
Related Article

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.