LeetCode 191. Number of 1 Bits

来源:互联网 发布:找网络推手联系方式 编辑:程序博客网 时间:2024/04/27 23:36

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.


// Need to pay attention to operators precedence and associativity, + and & are left to right associative. + precedence is higher than &. It is always good to add parenthesis if can't name the precedence and associativity.

int hammingWeight(uint32_t x) {    x =  ((x & 0x55555555) + ((x >> 1) & 0x55555555));    x = ((x & 0x33333333) + ((x >> 2) & 0x33333333));    x = ((x & 0x0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f));    x = ((x & 0x00ff00ff) + ((x >> 8) & 0x00ff00ff));    x = ((x & 0x0000ffff) + ((x >> 16) & 0x0000ffff));    return  x;  }// Another version.// it takes advantage of n & (n-1) which flips the right most '1' into '0'int countOneBits(int n) {    int count = 0;    while(n) {        count++;        n = n & (n-1);    }    return count;}
0 0
原创粉丝点击