二进制中1的个数
题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
解法1
经查阅 java 自带库中已有实现
public class Solution {
public int NumberOf1(int n) {
return Integer.bitCount(n);
}
}
###Integer 类中 bitCount 实现源码
/**
* Returns the number of one-bits in the two's complement binary
* representation of the specified {@code int} value. This function is
* sometimes referred to as the <i>population count</i>.
*
* @param i the value whose bits are to be counted
* @return the number of one-bits in the two's complement binary
* representation of the specified {@code int} value.
* @since 1.5
*/
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
此解法不好理解
解法2
等同于解法4
链接:https://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8
来源:牛客网
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while(n!= 0){
count++;
n = n & (n - 1);
}
return count;
}
}
解释:
如果一个整数不为0,那么这个整数至少有一位是1。如果我们把这个整数减1,那么原来处在整数最右边的1就会变为0,原来在1后面的所有的0都会变成1(如果最右边的1后面还有0的话)。其余所有位将不会受到影响。
举个例子:一个二进制数1100,从右边数起第三位是处于最右边的一个1。减去1后,第三位变成0,它后面的两位0变成了1,而前面的1保持不变,因此得到的结果是1011.我们发现减1的结果是把最右边的一个1开始的所有位都取反了。这个时候如果我们再把原来的整数和减去1之后的结果做与运算,从原来整数最右边一个1那一位开始所有位都会变成0。如1100&1011=1000.也就是说,把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.那么一个整数的二进制有多少个1,就可以进行多少次这样的操作。
解法3
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while(n != 0){
if((n & 1) != 0){
count++;
}
n = n >>> 1;
}
return count;
}
}
n 每次都是无符号右移一位,可避免当n为负数时,最高位总是1,从而引发死循环。
解法4
public class Solution {
public int NumberOf1(int n) {
int numOfOne = 0;
while(n != 0){
numOfOne++;
//n & -n 表示的是 n 从右到左第一个1所在的位置
//如n = 6,那么 n & -n 就是 2
n = n & (~(n & -n));
}
return numOfOne;
}
}
注:算法题目及其部分解法来源于牛客网-剑指offer