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.

题目含义:计算出给定数字中比特位为1的数量

 1     // you need to treat n as an unsigned value
 2     public int hammingWeight(int n) {
 3 //        return Integer.bitCount(n);
 4 
 5 //        方法二
 6         int count = 0;
 7 //        while (n != 0) {
 8 //            count += (n & 1);
 9 //            n = n >>> 1;
10 //        }
11 
12 //        方法三
13         while (n != 0) {
14             count++;
15             n &= (n - 1);
16         }
17 
18         return count;
19     }
原文地址:https://www.cnblogs.com/wzj4858/p/7727572.html