黑龙江网站建站建设/武汉网络推广有哪些公司
面试题15:二进制中1的个数
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数
// 常规解法
class Solution {
public:int hammingWeight(uint32_t n) {int count = 0;unsigned int flag = 1;while(flag){if(n&flag){count++;}flag = flag<<1;}return count;}
};
// 更有效率的解法
class Solution {
public:int hammingWeight(uint32_t n) {int count = 0;while(n){n = (n-1) & n;count++;}return count;}
};