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;
}