191.位1的个数
链接:191.位1的个数
难度:Easy
标签:位运算、分治
简介:编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。
题解 1 - typescript
- 编辑时间:2021-03-22
- 执行用时:100ms
- 内存消耗:39.4MB
- 编程语言:typescript
- 解法介绍:利用(n&n-1)可以去除末尾 1 的方式进行统计。
function hammingWeight(n: number): number {
let ans = 0;
while (n) {
n &= n - 1;
ans++;
}
return ans;
}
题解 2 - typescript
- 编辑时间:2021-03-22
- 执行用时:104ms
- 内存消耗:39.7MB
- 编程语言:typescript
- 解法介绍:二进制位移计算。
function hammingWeight(n: number): number {
let ans = 0;
for (let i = 0; i < 32; i++) ans += n & (1 << i) ? 1 : 0;
return ans;
}
题解 3 - typescript
- 编辑时间:2021-03-22
- 执行用时:112ms
- 内存消耗:39.8MB
- 编程语言:typescript
- 解法介绍:拆分字符串进行统计。
function hammingWeight(n: number): number {
return n
.toString(2)
.split('')
.filter(v => v === '1').length;
}