[LeetCode] 191. Number of 1 Bits

Meaning of the questions is to give a binary number, which calculated the number 1. This problem need to use a characteristic bit computing, the proposed back down, that is, n & (n-1) n will rightmost 1 to 0. So long as the mind a count, then look at this & operation several times, the entire digital becomes 0, it means that the process has been changed several 1 0 a. code show as below,

Time O (1) - is because bit operations, then how have only 32

Space O (1)

 1 /**
 2  * @param {number} n - a positive integer
 3  * @return {number}
 4  */
 5 var hammingWeight = function(n) {
 6     let res = 0;
 7     while (n !== 0) {
 8         n &= n - 1;
 9         res++;
10     }
11     return res;
12 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/11681978.html
Recommended