leetcode No191. Number of 1 Bits

来源:互联网 发布:会议速记软件 编辑:程序博客网 时间:2024/06/07 03:33

Question:

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.

求二进制中1的个数

Algorithm:

1、把1不断移位和num &,并不断计数可以得到1的个数

2、假设最右边的1在第m位,那么n-1的第m位为1,第m-1位到最右都为1,而n的第m位为1,第m-1位到最右都为0,这样n&(n-1)后,第m位到最右就全为0,计数+1。

循环这样的操作,直到n为0,结束循环。

Code:

算法1:

class Solution {public:    int hammingWeight(uint32_t n) {        int count=0;        uint32_t flag=1;        while(flag)        {            if(flag & n)                count++;            flag=flag<<1;        }        return count;    }};
算法2:

class Solution {public:    int hammingWeight(uint32_t n) {        int count=0;        while(n)        {            count++;            n=(n-1)&n;        }        return count;    }};




0 0
原创粉丝点击