您的位置:首页 > 其它

191. Number of 1 Bits

2016-07-26 16:34 253 查看
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 int hammingWeight(int n)
{
int cnt=0;
for(int i=0;i<32;i++)
{
if((n&0x1)==1)
cnt++;
n>>>=1;
}
return cnt;
}


方法2
https://discuss.leetcode.com/topic/9915/short-code-of-c-o-m-by-time-m-is-the-count-of-1-s-and-another-several-method-of-o-1-time
Each time of "n &= n - 1", we delete one '1' from n. (rightest one)


 O(m) by time, m is the count of
1's,

int hammingWeight(uint32_t n)
{
int res = 0;
while(n)
{
n &= n - 1;
++ res;
}
return res;
}


方法3

来自JDK1.5函数Integer.bitCount()源码

解释摘自http://bbs.csdn.net/topics/310240176

(以8bit为例):使用0x55作位运算也就是将X的位两两累加,如 11 01 10 11 两两累中后 得到 10 01 01 10, 
因为1+1=10  0+1=01  1+0=01 1+1=10 ,所以每二位一组标示X的二位的1的个数。
然后,以0x33对结果做位运算,为什么是0x33呢,因为结果是两位的,所以 是将其两位一组两两相加
得到  0011 0011 这一结果是四位一组的,每四位标示X的四位中的1的个数,
再使用0x0f做位运算,可想而知,得到的是八位组标示的X的每八位中的1的个数。因为X只有八位,所以到此结束

结果为 0011+0011=0000 0110 ,即6个1
更多位数以此类推

public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: