day154-LeetCode 191. Number of 1 Bits

题目

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

分析

先把数字转二进制,然后再遍历1的个数

题解

function hammingWeight () {
let secondS = n.toString(2).split('');
let count = 0
for (let i = 0; i < secondS.length; i++) {
if (secondS % 2 === 1) {
count++
}
}
return count
}
文章作者: lmislm
文章链接: http://lmislm.com/2019/06/16/2019-06-16/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog