题目
请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
示例
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof
思路
- 遍历字符串数1的个数
- 使用位运算,下面的实现使用的是位运算,通过n & (n - 1)去除最后1得到方法
实现
var hammingWeight = function(n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count++;
}
return count;
};