题解 | #二进制中1的个数#
二进制中1的个数
https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
int NumberOf1(int n) {
// write code here
int res = 0;
for(int i=0;i<32;i++){
if ((n & (1<<i)) != 0) {
res ++;
}
}
return res;
}
};
计算机储存数字都是用补码的形式,即正数的补码是原码,负数的补码是反码加一。因此只需要循环按位判断当前位是否为1,可通过与此位为1,其他位为0的数字进行按位与判断。注意判断条件为非0,而不是1,因为按位与得到的数值为2**n.
第二个解法为循环n=n&(n-1),直到n==0,循环次数即为1的数量。