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.

 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         n = n - ((n >>> 1) & 0x55555555);
 5         n = (n & 0x33333333) + ((n >>> 2) & 0x33333333);
 6         n = (n + (n >>> 4)) & 0x0f0f0f0f;
 7         n = n + (n >>> 8);
 8         n = n + (n >>> 16);
 9         return n & 0x3f;
10     }
11 }
 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int result = 0;
 5         while(n > 1){
 6             result += n % 2;
 7             n = (int)(n / 2);
 8         }
 9         if(n == 1) result ++;
10         return result;
11     }
12 }

it fail at n == 2147483648:

Because 2147483648 is not greater than 2147483648, and then shift to left 1 bit make bit == 0 instead of 2147483648 * 2. Then it fall into the infinity loop where bit always be 0.

 1 public class Solution {
 2     // you need to treat n as an unsigned value
 3     public int hammingWeight(int n) {
 4         int result = 0;
 5         for(int i = 0; i < 32; i ++){
 6             if(((n>>i)&1) == 1) result ++;
 7         }
 8         return result;
 9     }
10 }
原文地址:https://www.cnblogs.com/reynold-lei/p/4365959.html