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.
第一时间想到十进制 转二进制的方法——除二取余,遂有了第一种方法
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
var num = n;
var count = 0;
while(num){
count +=num%2;
num = Math.floor(num/2);
}
return count;
};
没什么好说的
然后进行优化,摒弃除法取余的做法,采用和1位与,然后位右移的操作
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
<span style="white-space:pre"> </span>var count = 0;
<span style="white-space:pre"> </span>while(n){
<span style="white-space:pre"> </span>count +=n&1;
<span style="white-space:pre"> </span>n = n>>>1;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return count;
};
速度果断是有提升的。