191. 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.

Solution 1: Naive way: use mask to check every bit of the number.

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int res=0;
 5         int mask=1;
 6         for (int i=0;i<32;i++){
 7             if (n&mask) res++;
 8             mask<<=1;
 9         }            
10         return res;
11     }
12 };

Solution 2: line 7 uses n&n-1 to repeatedly flip the least-significant 1-bit of the number to 0 and add 1 to the result, until the number becomes 0. So we don't need to check every bit of the number.

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int res=0;
 5         while(n!=0){
 6             res++;
 7             n&=n-1;
 8         }
 9         return res;
10     }
11 };

Solution 3: https://en.wikipedia.org/wiki/Hamming_weight

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
 5         n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
 6         n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
 7         n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
 8         n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff);
 9         return (n);
10     }
11 };
原文地址:https://www.cnblogs.com/anghostcici/p/7341948.html