12. 191. Number of 1 Bits

bitwise operators

JavaScript Bitwise Operators (with Examples)

with bitwise

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function (n) {
    let cnt = 0;
    while (n ^ 0) {
        cnt = cnt + (n & 1);
        n = n >>> 1;
    }
    return cnt;
};

without bitwise

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
const memo = {};
var hammingWeight = function(n) {
    if (memo[n] !== undefined) return memo[n];
    const bi = n.toString(2);
    let cnt = 0;
    for (let i = 0; i < bi.length; i++) {
        if (bi.charAt(i) === '1') cnt++;
    }
    memo[n] = cnt;
    return cnt
};

Last updated