题解 | #二进制中1的个数#
二进制中1的个数
https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu
做C++练习题学到的。
n & n - 1 统计二进制中1的个数,这里考虑负数的情况需要先将其转换为无符号整数
统计二进制0的个数,使用 n | n + 1
class Solution {
public:
int NumberOf1(int n) {
int res = 0;
// 将其转为无符号整数
unsigned int num = n;
while (num > 0) {
++res;
// 每次消除一个1
num = num & (num - 1);
}
return res;
}
};