LeetCode-191.Number of 1 Bits

来源:互联网 发布:办户外婚礼多少钱知乎 编辑:程序博客网 时间:2024/05/21 22:56

https://leetcode.com/problems/number-of-1-bits/

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.

显然用到位操作的办法

int hammingWeight(uint32_t n)     {        int res = 0;    while (n > 0)    {    if (n & 1 == 1)    res++;    n >>= 1;    }    return res;    }

方法2

同样是位操作,利用n&(n-1)的操作:把n的最低位1置0。这个技巧在题231.Power of Two 也用到了

int hammingWeight(uint32_t n)     {        int res = 0;    while (n > 0)    {    n &= (n - 1);    res++;    }    return res;    }


0 0
原创粉丝点击