题解 | #牛群的编码统计#
牛群的编码统计
https://www.nowcoder.com/practice/89500cbfd12a4c9f893aafb3c308baa2
知识点
位运算
思路
利用数字的位运算,不断将n右移,根据最后一位&1后的结果,统计32位中0的个数count。
代码c++
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
int countZeros(int n) {
// write code here
int count=0;
for (int i = 0; i < 32; ++i) {
if ((n & 1) == 0) {//最后一位为0
count++;
}
n >>= 1;//右移
}
return count;
}
};