191. Number of 1 Bits

Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
Example 1:
Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.
Example 2:
Input: n = 128
Output: 1
Explanation:
The input binary string 10000000 has a total of one set bit.
Example 3:
Input: n = 2147483645
Output: 30
Explanation:
The input binary string 1111111111111111111111111111101 has a total of thirty set bits.
Constraints:

  • 1 <= n <= 2<sup>31</sup> - 1

// eg. n = 11, binary= 1011
// everytime, we do n & 1 to check the lowest bits, if n&1 == 1, lowest bit is 1 otherwise 0;
// in order to check all bits, we shift right everytime, for unsighed int, it shifts all bits one place to the right, drop
// the least significant bits, and fill in leftmost bit with 0s.
// eg. n = 11, binary= 1011
// count == 0, n = 1011, n & 1 = 1, count ++
// count == 1, n = 101, n & 1 = 1, count++
// count == 2, n = 10, n&1 = 0
// count == 2, n = 1, n&1 = 1, count++
// count = 3
int hammingWeight(int n) {
    int count = 0;
    while (n != 0){
        if ((n & 1) == 1){
            count++;
        }
        n = n >> 1;
    }
    return count;
}

follow up questions:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容