Title Description
An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.
Ideas analysis
You must know common sense! All values in the computer memory's complement ! So I do not particularly concerned about the negative representation!
Look resolved before we know, there are basically three approaches.
Basic idea is that each and 1 with the operation, as is the bit is a 1, count ++. Question that arises is, after >> signed right shift, left complement positive number 0, 1 left up negative. If the number is negative, then into an infinite loop.
- A practice: unsigned right . After the right, whether positive or negative, on the left are 0s.
- Practice two: 32 1 determines left . int 32-bit type, regardless of the sign are determined from low to high 32 to the left.
- Practice three: n & n-1, n would become a rightmost 1 0 . There is an integer number 1, on how many such operations do.
Code
/**
* 无符号右移。正负数都补0.
* @param n
* @return
*/
public static int NumberOf1(int n) {
int count = 0;
while (n != 0) {
count += (n & 1);
n = n >>> 1;
}
return count;
}
/**
* 进行32次左移判断
* @param n
* @return
*/
public static int NumberOf12(int n) {
int count = 0, flag = 1;
while (flag != 0) {
count = (n & flag) != 0 ? count + 1 : 0;
flag <<= 1;
}
return count;
}
/**
* n & n-1 ,会把n最右一个1变成0
* @param n
* @return
*/
public static int NumberOf13(int n) {
int count = 0;
while (n != 0) {
count++;
n = (n - 1) & n;
}
return count;
}