Cosen95 / js_algorithm

🏂js数据结构与算法 系统学习
36 stars 10 forks source link

位1的个数 #52

Open Cosen95 opened 4 years ago

Cosen95 commented 4 years ago

位1的个数:https://leetcode-cn.com/problems/number-of-1-bits/

Cosen95 commented 4 years ago

思路分析

这里有一个小技巧, 可以轻松求出。 就是n & (n - 1) 可以消除 n 最后的一个1

如果对位运算比较了解的话,那么相信你一定对上述这条skill很熟悉🙈

这样我们可以不断进行n = n & (n - 1)直到n === 0 , 说明没有一个1了。通过count去计数即可~

代码实现

/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n) {
    let count = 0;
    while (n !== 0) {
        // n & (n - 1) 可以消除 n 最后的一个1
        n = n & (n-1)
        count++
    }
    return count
};