Leetcode 191 Number of 1 Bits

来源:互联网 发布:中铁四局网络采购平台 编辑:程序博客网 时间:2024/06/05 15:02

Leetcode 191 Number of 1 Bits

#include <stdint.h>using namespace std;class Solution {public:    int hammingWeight(uint32_t n) {        //n减1是将n最右边的那个1变成0,如果这个1后面跟着0,则这些0全变成1,相与可以得到最右边的1        //1111-1 = 1110,1000 - 1 = 0111,n&(n-1),每次会消掉最右边的那个0,        int count = 0;        while (n){            n = n &(n - 1);            count++;        }        return count;    }};
原创粉丝点击