力扣挑战赛第8天-No.191位1的个数

题目描述

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(汉明重量)。

示例:

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。

注意:

输入必须是长度为 32 的 二进制串

解法一

位运算

n & n - 1,将会使 n 对应的二进制串的最低位 1 置为 0

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number} n - a positive integer
* @return {number}
*/
let hammingWeight = function (n) {
let ret = 0;
while (n) {
n &= n - 1;
ret++;
}
return ret;
};

解法二

位运算 + 左移

将 n 对应的二进制串的每一位与 1 进行 & 运算

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* @param {number} n - a positive integer
* @return {number}
*/
let hammingWeight = function (n) {
let ret = 0;
for (let i = 0; i < 32; i++) {
if (n & (1 << i)) {
ret++;
}
}
return ret;
};

解法三

懒蛋法

1
2
3
let hammingWeight = function (n) {
return n.toString(2).split('').filter((item) => item === '1').length;
};
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信